透视 2 行 bigquery
Pivot 2 rows bigquery
如何将 2 行旋转成列?
ID|col_1|col_2|col_3|col_4
1 |a |A |Q |5000
1 |a |B |Q |8000
2 |a |A |R |4000
2 |a |B |T |6000
进入:
ID|col_1|A_col3|A_col4|B_col3|B_col4
1 |a |Q |5000 |R |4000
2 |a |Q |8000 |T |6000
col_2 中的值现在是列标题,col_3 和 col_4 中的值是主元中的放大值。
我试过了,但坚持下一步,没有给出想要的结果:
select * from
(
select ID, col_1, col_2, col_3, col_4 from tableA
) as A
pivot (max(col_3) for col_2 in ('A','B'))
只使用条件聚合:
select id,
max(case when col_2 = 'A' then col_3 end) as a_col3,
max(case when col_2 = 'A' then col_4 end) as a_col4,
max(case when col_2 = 'B' then col_3 end) as b_col3,
max(case when col_2 = 'B' then col_4 end) as b_col4
from tablea
group by id;
I tried this but stuck on the next step ...
考虑以下方法
select *
from tableA
pivot (max(col_3) as col3, max(col_4) as col4 for col_2 in ('A', 'B'))
如果应用于您问题中的示例数据 - 输出为
如何将 2 行旋转成列?
ID|col_1|col_2|col_3|col_4
1 |a |A |Q |5000
1 |a |B |Q |8000
2 |a |A |R |4000
2 |a |B |T |6000
进入:
ID|col_1|A_col3|A_col4|B_col3|B_col4
1 |a |Q |5000 |R |4000
2 |a |Q |8000 |T |6000
col_2 中的值现在是列标题,col_3 和 col_4 中的值是主元中的放大值。
我试过了,但坚持下一步,没有给出想要的结果:
select * from
(
select ID, col_1, col_2, col_3, col_4 from tableA
) as A
pivot (max(col_3) for col_2 in ('A','B'))
只使用条件聚合:
select id,
max(case when col_2 = 'A' then col_3 end) as a_col3,
max(case when col_2 = 'A' then col_4 end) as a_col4,
max(case when col_2 = 'B' then col_3 end) as b_col3,
max(case when col_2 = 'B' then col_4 end) as b_col4
from tablea
group by id;
I tried this but stuck on the next step ...
考虑以下方法
select *
from tableA
pivot (max(col_3) as col3, max(col_4) as col4 for col_2 in ('A', 'B'))
如果应用于您问题中的示例数据 - 输出为