我编写了一个包含大量联接的查询,它给了我这样的结果。
下面的列和数据
RecordID | Person Name | Comments | Date
1 | ABC | aaa | 22-05-2020
2 | XYZ | bbb | 11-11-1111
1 | QWERTY | aaa | 22-05-2020
3 | ASDASDSA |oooo |
现在我需要ID记录ID是相同的,那么它的人名应该在一行中显示为逗号分隔值
所需的输出如下:
RecordID | Person Name | Comments | Date
1 | ABC ,QWERTY | aaa | 22-05-2020
2 | XYZ | bbb | 11-11-1111
3 | ASDASDSA |oooo |
用于获取此数据的查询非常复杂。
这是一个有效的示例,在该示例中,我们使用row_number()
维护序列,并使用stuff / XML方法聚合字符串。 (2012年兼容)
示例
Set Dateformat DMY
Declare @YourTable Table ([RecordID] int,[Person Name] varchar(50),[Comments] varchar(50),[Date] date)
Insert Into @YourTable Values
(1,'ABC','aaa','22-05-2020')
,(2,'XYZ','bbb','11-11-1111')
,(1,'QWERTY','aaa','22-05-2020')
,(3,'ASDASDSA','oooo',null)
;with cte as (
Select *
,RN = row_number() over (partition by RecordID Order by Date Desc)
from @YourTable
)
Select [RecordID]
,[Person Name] = stuff((Select ',' +[Person Name] From cte Where [RecordID]=A.[RecordID] Order By RN For XML Path ('')),1,1,'')
,[Comments] = max(case when RN=1 then [Comments] end)
,[Date] = max(case when RN=1 then [Date] end)
From cte A
Group By RecordID
返回
RecordID Person Name Comments Date
1 ABC,QWERTY aaa 2020-05-22
2 XYZ bbb 1111-11-11
3 ASDASDSA oooo NULL