求一条组合字符串的sql
a name c
001 abc 鞍山
002 bcd 沈阳
003 bcd 沈阳
004 bcd 大连
005 cdf 大连
006 cdf 大连
现在想得到的结果是
a name c
001 abc 鞍山
002,003 bcd 沈阳
004 bcd 大连
005,006 cdf 大连
如果name和c字段都相同,则合并用逗号分隔
[解决办法]
;with cte as(
select '001' as a,'abc' as name,'鞍山' as c
union all select '002','bcd','沈阳'
union all select '003','bcd','沈阳'
union all select '004','bcd','大连'
union all select '005','cdf','大连'
union all select '006','cdf','大连'
)
select stuff((select ','+a from cte b
where b.c=a.c and a.name=b.name
for xml path('')),1,1,'') 'a'
,a.name,a.c
from cte a
group by a.name,a.c
order by c
/*
anamec
001abc鞍山
004bcd大连
005,006cdf大连
002,003bcd沈阳
*/
if OBJECT_ID('tempdb..#temp', 'u') is not null drop table #temp;
go
create table #temp( [a] varchar(100), [name] varchar(100), [c] varchar(100));
insert #temp
select '001','abc','鞍山' union all
select '002','bcd','沈阳' union all
select '003','bcd','沈阳' union all
select '004','bcd','大连' union all
select '005','cdf','大连' union all
select '006','cdf','大连'
--SQL:
SELECT
a = STUFF((SELECT ','+a FROM #temp b WHERE b.c=a.c AND b.name=a.NAME ORDER BY b.a FOR XML PATH('')),1,1,''),
a.NAME,
a.c
FROM #temp A
GROUP BY a.name, a.c
ORDER BY MIN(a.a)
/*
aNAMEc
001abc鞍山
002,003bcd沈阳
004bcd大连
005,006cdf大连
*/
SELECT a = STUFF(
(SELECT ','+[a],t2.[name],t2.c FROM [Table_3] t1
WHERE t1.[name]=t2.[name] AND t1.[c] =t2.[a] ORDER BY t1.a DESC FOR XML PATH('')),1,1,'')
FROM [Table_3] t2 GROUP BY t2.[name],t2.[c]