sql—如何按类型计算值并将列转换为行

mwg9r5ms  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(257)

我有一个表“tbtest1”,如下所示:

q1 | q2 | q3 | type
---+----+----+-----------
 3 |  2 |  2 | Student
 2 |  2 |  3 | Student
 3 |  1 |  1 | Alumni
 1 |  1 |  3 | Student
 1 |  3 |  2 | Alumni

现在我想把“tbtest1”转换成这样,学生给了“q1”、“q2”和“q3”多少个1、2或3:

q  | 1 | 2 | 3
---+---+---+---
q1 | 1 | 1 | 1
q2 | 1 | 2 | 0
q3 | 0 | 1 | 2
vdgimpew

vdgimpew1#

可以使用条件聚合:

select v.q,
       sum(case when val = 1 then 1 else 0 end) as val_1,
       sum(case when val = 2 then 1 else 0 end) as val_2,
       sum(case when val = 3 then 1 else 0 end) as val_3
from tbTest t cross apply
     (values ('q1', t.q1), ('q2', t.q2), ('q3', t.q3)) v(q, val)
where t.type = 'student'
group by v.q;

相关问题