pivot将行转换为列(包含其他行数据)

pxyaymoc  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(433)

有人能帮我处理这个sql吗?
我正在寻找轴多行成列:id,类型,颜色,日期
挑战:我想在数据透视表上保留/显示多个列。

id | type   | color  | date      | country_code | cost
---+--------+--------+-----------+--------------+-------
1  | report | red    | 2020-09-01| US           | 1
1  | report | red    | 2020-09-01| EU           | 2
1  | report | red    | 2020-09-01| RU           | 3
1  | report | red    | 2020-09-01| AP           | 4
1  | report | blue   | 2020-09-02| US           | 5   
1  | report | blue   | 2020-09-02| EU           | 6
1  | report | blue   | 2020-09-02| RU           | 7
1  | report | blue   | 2020-09-02| AP           | 8
2  | report | green  | 2020-09-02| US           | 9
2  | report | green  | 2020-09-02| EU           | 10
2  | report | green  | 2020-09-02| RU           | 11
2  | report | green  | 2020-09-02| AP           | 12
2  | report | blue   | 2020-09-03| US           | 13
2  | report | blue   | 2020-09-03| EU           | 14
2  | report | blue   | 2020-09-03| RU           | 15
2  | report | blue   | 2020-09-03| AP           | 16

期望输出:

id | type   | color | date       | US | EU | RU | AP
---+--------+-------+------------+----+----+----+----
1  | report | red   | 2020-09-01 | 1  | 2  | 3  | 4
1  | report | blue  | 2020-09-02 | 5  | 6  | 7  | 8
2  | report | green | 2020-09-02 | 9  | 10 | 11 | 12
2  | report | blue  | 2020-09-03 | 13 | 14 | 15 | 16

已知信息:
只有4个国家代码。
这个 color 值将根据以下各项相同:id、类型、日期。
不知道写这个sql最干净/最好的方法是什么。
我试过使用

ROW_NUMBER() OVER(PARTITION BY xxx ORDER BY yyy)

以及 PIVOT 但却得不到我想要的结果

jbose2ul

jbose2ul1#

我认为条件聚合可以满足您的要求:

select id, type, color, date,
       max(case when country_code = 'US' then cost end) as us,
       max(case when country_code = 'EU' then cost end) as eu,
       max(case when country_code = 'RU' then cost end) as ru,
       max(case when country_code = 'AP' then cost end) as AP
from t
group by id, type, color, date;
igetnqfo

igetnqfo2#

我到处玩,觉得我得到了这个:

SELECT id, type, color, date, [US], [EU], [RU], [AP]
FROM
(
  SELECT id, type, color, date, country_code, cost FROM tableX
) t
PIVOT
(
  MAX(cost)
  FOR country_code IN ( [US], [EU], [RU], [AP] )
) p

相关问题