嵌套的枢轴列[重复]
Posted
技术标签:
【中文标题】嵌套的枢轴列[重复]【英文标题】:Nested pivot columns [duplicate] 【发布时间】:2021-03-31 04:00:36 【问题描述】:我有一张桌子销售:
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
如何修改?
【问题讨论】:
【参考方案1】:您可以按如下方式使用条件聚合:
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;
【讨论】:
【参考方案2】:首先,您需要一个定义行顺序的列 - 我假设为 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
【讨论】:
以上是关于嵌套的枢轴列[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何将具有嵌套元素的列从其他列添加到数据框(withColumn)[重复]