我有一个包含很多记录的表。它具有以下结构:
表格(col1,col2,col3,col4,col5,col6):
a b c val1 val2 val3
d e f val4 val5 val6
d e f val7 val8 val9
g h i val10 val11 val12
g h i val13 val14 val15
g h i val16 val17 val18
还有许多其他行。
因此,我想要一张桌子:
表(col1,col2,col3,col4_1,col4_2,col4_3,col5_1,col5_2,col5_3,col6_1,col6_2,col6_3):
a b c val1 val2 val3 null null null null null null
d e f val4 val5 val6 val7 val8 val9 null null null
g h i val10 val11 val12 val13 val14 val15 val16 val17 val18
换句话说:我有部分表具有相同的col1, col2, col3
但有不同的col4, col5, col6
。每个相同的col1, col2, col3
的行数在1-3之间(事先未知)。
我的想法是使用GROUP BY
,但如何处理可以在动态行数中满足的col4, col5, col6
值呢?
如何制作这种桌子?
答案 0 :(得分:1)
您可以使用条件聚合和row_number()
:
select col1, col2, col3,
max(case when seqnum = 1 then col4 end) as col4_1,
max(case when seqnum = 1 then col5 end) as col5_1,
max(case when seqnum = 1 then col6 end) as col6_1,
max(case when seqnum = 2 then col4 end) as col4_2,
max(case when seqnum = 2 then col5 end) as col5_2,
max(case when seqnum = 2 then col6 end) as col6_2,
max(case when seqnum = 3 then col4 end) as col4_3,
max(case when seqnum = 3 then col5 end) as col5_3,
max(case when seqnum = 3 then col6 end) as col6_3
from (select t.*, row_number() over (partition by col1, col2, col3 order by col1) as seqnum
from t
) t
group by col1, col2, col3