首页 > 解决方案 > 旋转重复项的最佳方法是什么?

问题描述

我有下表:

在此处输入图像描述

SQL Server 中旋转该表的最佳方法是什么,使其看起来像这样:

在此处输入图像描述

标签: sqlsql-serverduplicatespivotwindow-functions

解决方案


您可以使用row_number()条件聚合:

select key,
    max(case when rn = 1 then email end) email1,
    max(case when rn = 2 then email end) email2,
    max(case when rn = 3 then email end) email3
from (
    select t.*, row_number() over(partition by key order by email) rn
    from mytable t
) t
group by key

您可以在子句中添加更多条件max()s 以select处理超过 3 emails per key


推荐阅读