在不使用数据透视的情况下将行转换为列

时间:2019-10-07 21:08:13

标签: sql database

我有一个数据集,但示例数据如下图所示:

 Country Date       Category   X    Y
 IN     2011-11-22  B          1    0
 BA     2010-11-23  B         11    0.2
 IN     2011-11-22  A          1    0
 BA     2011-11-23  A          1    1
 IN     2011-07-28  A          1    0

想要将其转换为:输出

 Country Date       B_X    B_Y  A_X  A_Y
 IN     2011-11-22  1       0    1    0
 BA     2010-11-23  11      0.2  1    1
 IN     2011-07-28  0       0    1    0

我已经尝试过使用case了,但是它没有给我想要的输出,任何人都可以帮忙!

1 个答案:

答案 0 :(得分:5)

我认为您只想按country / date进行汇总并使用条件汇总:

select country, date,
       sum(case when category = 'B' then x end) as x_b,
       sum(case when category = 'B' then y end) as y_b,
       sum(case when category = 'A' then x end) as x_a,
       sum(case when category = 'A' then y end) as y_a
from t
group by country, date;