首页 > 解决方案 > 在不使用 Pivot 的情况下将行转换为列

问题描述

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

 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

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

标签: sqldatabase

解决方案


我认为您只想按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;

推荐阅读