嵌套数据透视列

Nested pivot columns

我有 table 销售额:

SalesID. Date. Geography

1.       2020-01.  Italy
1.       2020-01.  France
1.       2020-01.  UK
2.       2020-02.  Italy
2.       2002-02.  Canada
3.       2002-08.  France

我只想显示前 2 个地理位置和数据透视:

预期结果:

SalesID.   Date. Geography 1.    Geography2.
1.      2020-01. Italy. France

2.     2020-02.  Italy.  France.
3.    2020-08.    France

到目前为止我尝试了什么https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=565f80f146fe2a72096b31fc0baba3ad

如何修改?

首先,您需要一个定义行顺序的列 - 我假设 ordering_id。然后,您可以使用 row_number() 和条件聚合。

select saleid, date,
    max(case when rn = 1 then geography end) as geography1,
    max(case when rn = 2 then geography end) as geography2
from (
    select t.*,
        row_number() over(partition by saleid, date order by ordering_id) as rn
    from mytable t
) t
where rn <= 2
group by saleid, date

您可以按如下方式使用条件聚合:

select t.sales_id,
       date, 
       max(CASE WHEN rn = 1 THEN geography END) AS geography1,
       max(CASE WHEN rn = 2 THEN geography END) AS geography2
(select t.*, row_number() over (partition by t.sales_id, date order by t.date) as rn
FROM your_table t) t
GROUP BY t.sales_id, date;