如何使用 GROUP BY 修改 SQL SELECT 请求

How to modify a SQL SELECT request with GROUP BY

我正在使用以下 SQL Informix DB 请求:

select fromQ, toQ, count(callid) as cont_num, type
from some_table
group by fromQ, toQ, type
order by fromQ, toQ;

它产生结果:

fromq   toq        cont_num  type
-----------------------------------
        Sales      12        1
        English    1         1
        MB         59        1
        Reception  3         2
        Reception  53        1
        Service    1         1
MB      Sales      1         1
MB      English    1         1

这没问题,符合预期。请注意 toq=Reception 有 2 行。 字段 WRTYPE 的值只能从 1 到 3。 所以想法是做出这样的输出:

fromq   toq        cont_num  type1  type2  type3
------------------------------------------------
        Sales      12        12     0      0
        English    1         1      0      0
        MB         59        59     0      0
        Reception  56        53     3      0
        Service    1         1      0      0
MB      Sales      1         1      0      0
MB      English    1         1      0      0

有没有简单的方法可以做到这一点?

使用条件聚合:

select fromQ, toQ, count(callid) as cont_num,
       sum(case when type = 1 then 1 else 0 end) as type_1,
       sum(case when type = 2 then 1 else 0 end) as type_2,
       sum(case when type = 3 then 1 else 0 end) as type_3
from some_table
group by fromQ, toQ
order by fromQ, toQ;