【发布时间】:2018-05-07 13:41:01
【问题描述】:
实际数据格式如下:
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
使用 UNPIVOT 的结果:
Id | Expiring Date | Disclouser
1 | 2017-05-03 | Photo DisclosureDate
1 | 2017-05-03 | Community Trip Disclosure
1 | 2017-06-03 | Assum Of Risk Disclosure
1 | 2017-06-03 | Release Of Info
2 | 2017-07-03 | Photo DisclosureDate
预期结果:
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 命令中对项目进行分组。
【问题讨论】:
-
您使用的是哪个 dbms?
-
样本数据真的很有帮助。
标签: sql sql-server group-by unpivot