SQL 分块帮助 'pivoting' table

SQL Help 'pivoting' a table in chunks

我的数据库 table 是这样的,每个条目都在每个图表的新行中列出。我想 'pivot' 并按 ID 分组。我需要使用一堆 CASE WHEN 语句还是这是一种简洁的方法?

这是一个简化的 table:

Chart_ID 规则 动作
A1 R1 Y
A1 R3 N
B4 R1 N
C1 R1 Y
C1 R2 N
C1 R3 Y

我想要一个 table 这样的:

Chart_ID R1 动作 1 R2 动作 2 R3 动作 3 R4 动作 4
A1 R1 Y R3 N
B4 R1 N
C1 R1 Y R2 N R3 Y

您可以使用条件聚合:

select chart_id,
       max(case when rule = 'R1' then rule end) as r1,
       max(case when rule = 'R1' then action end) as action1,
       max(case when rule = 'R2' then rule end) as r2,
       max(case when rule = 'R2' then action end) as action2,
       max(case when rule = 'R3' then rule end) as r3,
       max(case when rule = 'R3' then action end) as action3,
       max(case when rule = 'R4' then rule end) as r4,
       max(case when rule = 'R4' then action end) as action4
from t
group by chart_id;

请注意,R1R2R3R4 列是可疑的,因为它们是多余的。正如您定义的数据,action1 用于规则 'R1'