如何使枢轴不止一个列值sql

时间:2018-12-15 19:00:35

标签: sql sql-server pivot

我有这张桌子

     country weeek  quantity 1  quantity 2  quantity 3
0        1    sa        3235         365         123
1        1    su        6698       32135        1234
2        1    mo        1565        5689       12345

所需的输出:

   country  sa_q1  su_q1  mo_q1  sa_q2  su_q2  mo_q2  sa_q3  su_q3  mo_q3
0        1   3235   6698   1565    365  32135   5689    123   1234  12345

1 个答案:

答案 0 :(得分:1)

只需使用条件聚合:

select country,
       sum(case when week = 'sa' then quantity1 else 0 end) as sa1,
       sum(case when week = 'su' then quantity1 else 0 end) as su1,
       sum(case when week = 'mo' then quantity1 else 0 end) as mo1,
       sum(case when week = 'sa' then quantity2 else 0 end) as sa2,
       sum(case when week = 'su' then quantity2 else 0 end) as su2,
       sum(case when week = 'mo' then quantity2 else 0 end) as mo2,
       sum(case when week = 'sa' then quantity3 else 0 end) as sa3,
       sum(case when week = 'su' then quantity3 else 0 end) as su3,
       sum(case when week = 'mo' then quantity3 else 0 end) as mo3
from t
group by country;
相关问题