具有多行行数据的多列到单行&对于非重复数据需要连接

时间:2017-03-31 21:29:37

标签: sql sql-server tsql

Currently data is like below:-

enter image description here

SQL Query:-
declare @t table
(
    Id int,
    ReportedDate DATE,
    [Name] varchar(10)
)
insert into @t

select 1,'2016-01-01','ab' union all
select 2,'2016-01-01','a' union all
select 1,'2016-01-20','hha' union all
select 2,'2016-01-20','jnsjja' union all
select 1,'2016-01-01','jsjb' union all
select 2,'2016-01-01','sjjjwb' union all
select 1,'2016-01-20','bjd' union all
select 2,'2016-01-20','bwjw'

select * from @t order by id, ReportedDate

预期结果: -

enter image description here

如果我们只有2列,一个是Id&另一个是什么。但对于多列,我无法

1 个答案:

答案 0 :(得分:0)

然而,有无数的例子,因为你有一个很容易复制和粘贴的结构很好的问题....

Select A.ID 
      ,A.ReportedDate
      ,Name  = Stuff((Select Distinct ',' +Name From @t Where ID=A.ID and ReportedDate=A.ReportedDate For XML Path ('')),1,1,'') 
 From (Select Distinct ID,ReportedDate From @t ) A

返回

ID  ReportedDate    Name
1   2016-01-01      ab,jsjb
1   2016-01-20      bjd,hha
2   2016-01-01      a,sjjjwb
2   2016-01-20      bwjw,jnsjja