【问题标题】:STUFF, UNPIVOT and group By clause on data数据上的 STUFF、UNPIVOT 和 group By 子句
【发布时间】: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


【解决方案1】:

我想你想要:

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() 聚合功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多