Sql 从行中添加自定义列

Sql 从行中添加自定义列,sql,sql-server,pivot,multiple-columns,rows,Sql,Sql Server,Pivot,Multiple Columns,Rows,我想编写一个查询,将行旋转到具有自定义列名的列 以下是我的示例输出: Name Documents Sent ---- ------------------ ---------- Paul Attachment1 - Paul 2020-01-01 Paul Attachment2 - Paul 2020-01-01 Ty Attachment1 - Ty 2020-01-02 我的期望输出: Name Attachment1 Attachment1Se

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

以下是我的示例输出:

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。我相信我可以使用
PIVOT
CROSS-APPLY
来实现这一点,但我一直在研究如何创建自定义列名。欢迎提供任何帮助或建议。谢谢大家!

您可以使用条件聚合:

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;

我们需要看看你试过什么。