【问题标题】:Add custom columns from rows从行添加自定义列
【发布时间】:2021-05-27 05:55:56
【问题描述】:

我想编写一个查询,将行转换为具有自定义列名的列。

这是我的示例输出:

Name Documents          Sent
---- ------------------ ----------
Paul Attachment1 - Paul 2020-01-01
Paul Attachment2 - Paul 2020-01-01
Ty   Attachment1 - Ty   2020-01-02

我想要的输出:

Name Attachment1        Attachment1Sent Attachment2        Attachment2Sent
---- ------------------ --------------- ------------------ ---------------
Paul Attachment1 - Paul 2020-01-01      Attachment2 - Paul 2020-01-01
Ty   Attachment1 - Ty   2020-01-02      NULL               NULL

文档数量最多为两个,但最少只有一个。

我正在使用 SQL Server。我相信我可以使用PIVOTCROSS APPLY 来做到这一点,但我被困在如何创建自定义列名上。任何帮助或建议表示赞赏。谢谢!

【问题讨论】:

  • 我们需要看看你的尝试。

标签: sql sql-server pivot multiple-columns rows


【解决方案1】:

您可以使用条件聚合:

select name, 
       max(case when seqnum = 1 then document end) as document_1,
       max(case when seqnum = 1 then sent end) as sent_1,
       max(case when seqnum = 2 then document end) as document_2,
       max(case when seqnum = 2 then sent end) as sent_2
from (select t.*,
             row_number() over (partition by name order by sent) as seqnum
      from t
     ) t
group by name;

【讨论】:

    猜你喜欢
    • 2018-02-03
    • 2013-03-01
    • 1970-01-01
    • 2011-11-18
    • 2013-11-10
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多