将第一个记录的单个列与SQLServer中的重复记录合并

时间:2016-08-19 07:59:54

标签: sql sql-server

我在sqlserver

中有这些数据
ID Phone 
1   100
1   200
2   300
2   300
3   400
3   500
3   600

我想要这样的输出

ID Phone 
1   100,200
1   200 
2   300
2   300
3   400,500,600
3   500
3   600

1 个答案:

答案 0 :(得分:0)

;with cte
as
(select id,phone,
stuff((select  distinct','+cast(phone as varchar(20))
from #valuee t2 where t1.id=t2.id
for xml path('')),1,1,'') as nwphone
from #valuee t1
)
select id,
case when 1=dense_rank() over (partition by id,nwphone order by phone) 
then cast(nwphone as varchar(20)) else cast(phone as varchar(20)) end as phone
from
cte

输出

id  phone
1   100,200
1   200
2   300
2   300
3   400,500,600
3   500
3   600