Sql 数据上的STUFF、UNPIVOT和groupby子句
实际数据采用以下格式:Sql 数据上的STUFF、UNPIVOT和groupby子句,sql,sql-server,group-by,unpivot,Sql,Sql Server,Group By,Unpivot,实际数据采用以下格式: Id | Disclosure | Photo DisclosureDate | Community Trip Disclosure | Assum Of Risk Disclosure | Release Of Info | Photo DisclosureDate 1 | 2017-05-03 | 2017-05-03 | 2017-05-03 | 2017-05-03
Id | Disclosure | Photo DisclosureDate | Community Trip Disclosure | Assum Of Risk Disclosure | Release Of Info | Photo DisclosureDate
1 | 2017-05-03 | 2017-05-03 | 2017-05-03 | 2017-05-03 | 2017-05-03 | 2017-05-03
2 | 2017-05-03 | 2017-05-03 | 2017-05-03 | 2017-05-03 | 2017-05-03 | 2017-05-03
使用UNPIVOT从每个列获取单独行中的数据日期可能不同,因此对于每个唯一的日期,需要逗号分隔的列名:
SELECT Id, t1.ExpiringOn ,DisclouserName
FROM (SELECT Id, ParticipantName, ExpiringOn, DisclouserName FROM (
SELECT P.Id, P.LastName + ', ' + P.FirstName as 'ParticipantName', TSL.PhotoDisclosureDate, TSL.CommunityTripDisclosureDate, TSL.AssumOfRiskDisclosureDate, TSL.ReleaseOfInfoDate, TSL.DisclosureDate
FROM RegistrationDisclosures AS TSL
INNER JOIN RegistrationParticipantInfo AS P with (nolock) ON P.Id = TSL.ParticipantId
where P.IsActive = 1 and (TSL.PhotoDisclosureDate < GETDATE() or TSL.CommunityTripDisclosureDate < GETDATE() or TSL.AssumOfRiskDisclosureDate < GETDATE() or TSL.ReleaseOfInfoDate < GETDATE() or TSL.DisclosureDate < GETDATE())
) d
UNPIVOT
(
ExpiringOn for DisclouserName in (PhotoDisclosureDate, CommunityTripDisclosureDate, AssumOfRiskDisclosureDate, ReleaseOfInfoDate, DisclosureDate)
) upvt) t1
预期结果:
Id | Expiring Date | Disclouser
1 | 2017-05-03 | Photo DisclosureDate, Community Trip Disclosure
1 | 2017-06-03 | Assum Of Risk Disclosure, Release Of Info
2 | 2017-07-03 | Photo DisclosureDate
正在尝试使用STUFF,但无法在STUFF命令中对项目进行分组。我想您需要:
WITH x as (<your query here>)
SELECT x.id, x.expiringon,
STUFF( (SELECT ', ' + DisclouserName
FROM x x2
WHERE x2.id = x.id
FOR XML PATH ('')
), 1, 2, ''
)
FROM (SELECT DISTINCT id, expiringon FROM x) x;
这是聚合字符串连接的XML版本。SQL Server的最新版本最终提供了一个字符串聚合函数。您使用的是哪种dbms?示例数据将非常有用。
WITH x as (<your query here>)
SELECT x.id, x.expiringon,
STUFF( (SELECT ', ' + DisclouserName
FROM x x2
WHERE x2.id = x.id
FOR XML PATH ('')
), 1, 2, ''
)
FROM (SELECT DISTINCT id, expiringon FROM x) x;