我正在对Informix DB使用以下SQL请求:
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;