SQL基础知识--多⾏查询结果拼接
今天在⼯作中遇到如下这个问题,需要将如下的查询结果,拼接成⼀⾏!
1select PERSON_NAME from S_PROJECT_MEMBER where PROJECT_ID ='2c9081473e2f8bda013e3028e4700049';
先直接上代码吧!-------------------------有问题的,⿇烦指出--------------------------------------------------------
select
CAST(stuff((
select distinct','+PERSON_NAME
from S_PROJECT_MEMBER
where PROJECT_ID ='2c9081473e2f8bda013e3028e4700049'for xml path('')),1,1,'') AS varchar(1000)
)
AS PERSON_NAMES
from S_PROJECT_MEMBER
where PROJECT_ID ='2c9081473e2f8bda013e3028e4700049'GROUP BY PROJECT_ID;
这⾥⽤的知识点有:
for xml path() 函数:
--这⾥⽤来做字符串拼接
CAST()函数:
--CAST函数⽤于将某种数据类型的表达式显式转换为另⼀种数据类型
cast( "abcdefg" as varchar(2000));
STUFF()函数:
--STUFF()函数⽤于删除指定长度的字符,并可以在制定的起点处插⼊另⼀组字符。
--select stuff(列名,开始位置,长度,替代字符串)
DISTINCT 关键字:
--这⾥可以理解为去重,具体可以百度
AS 关键字:
--取别名
GROP BY :
select中distinct--⽤于分组
下⾯通过具体的例⼦来说明吧:来⾃于:wwwblogs/doubleliang/archive/2011/07/06/2098775.html
create table hobby(
hobbyId varchar(32),
hName varchar(32)
)
insert into hobby values('1','爬⼭');
insert into hobby values('2','游泳');
insert into hobby values('3','爬⼭');
--将查询结果根据⾏输出成XML格式
SELECT*FROM hobby FOR XML PATH;
--改变XML⾏节点的名称
SELECT*FROM hobby FOR XML PATH('MyHobby');
--改变XML列节点的名称
SELECT hobbyID as'MyCode',hName as'MyName'FROM hobby FOR XML PATH('MyHobby');
--构建我们喜欢的输出⽅式
SELECT'[ '+hName+' ]'FROM hobby FOR XML PATH('');
现在我对例⼦进⾏应⽤:
--应⽤
select distinct','+hobbyId from hobby for xml path('');
-- for xml path('') 解决连接问题
select hName,(select distinct'+'+hobbyId from hobby h where h.hName = hName for xml path('')) AS A
from hobby
group by hName;
-- stuff(String,1,1,'') 去除开始的连接符 +1+2+3 --> 1+2+3
select hName,stuff((select distinct'+'+hobbyId from hobby for xml path('')),1,1,'') AS A
from hobby
group by hName;
-
-需要查询结果
'爬⼭' '1'+'3'
'游泳' '2'
--⽅法⼀
select hName,stuff((select distinct'+'+hobbyId from hobby where hName = B.hName for xml path('')),1,1,'') AS A from hobby B
group by hName;
--⽅法⼆
SELECT B.hName,LEFT(StuList,LEN(StuList)-1) as hobby FROM (
SELECT hName,
(SELECT hobbyId+','FROM hobby
WHERE hName=A.hName
FOR XML PATH('')) AS StuList
FROM hobby A
GROUP BY hName
) B
结果:
第⼀次写笔记。。。。。2016.06.25
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论