数据的STUFF,UNPIVOT和group By子句

时间:2018-05-07 13:41:01

标签: 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               | 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命令中对项目进行分组。

1 个答案:

答案 0 :(得分:0)

我想你想要:

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最终提供了string_agg()聚合函数。