我有这个查询,我必须计算多个字段
select
distinct(custsegment),
(select count(distinct clid) from call_log where enteredon = '16-JUL-13') as UniqCalls,
(select count(disconnectflag) from call_log where disconnectflag='IVR' and enteredon = '16-JUL-13') as IvrCalls,
(select count(callerid) from call_log where enteredon = '16-JUL-13') as TotalCalls
from call_log
where enteredon = '16-JUL-13'
输出
CUSTSEGMENT UNIQCALLS IVRCALLS TOTALCALLS
------------ ---------- ---------- ----------
PRIORITY 12 6 12
NORMAL 12 6 12
但问题似乎是我获得了PRIORITY和NORMAL CUSTSEGMENT的相同值,我也不确定这是否是计算它的正确方法。请建议。
答案 0 :(得分:3)
我认为你的意思是group by
。这也使您的查询更简单,因为您不需要子选择。
select
custsegment,
count(distinct clid) as UniqCalls,
count(case when disconnectflag = 'IVR' then 1 else null end) as IvrCalls,
-- sum(case when disconnectflag = 'IVR' then 1 else 0 end) as IvrCalls,
count('x') as TotalCalls
from call_log
where enteredon = '16-JUL-13'
group by
custsegment
要计算IvrCalls,您可以通过几种方式进行计算。 Count
计算所有非空值,因此您可以使用案例(您甚至可以省略else null
)。或者您也可以使用常用的sum
。
答案 1 :(得分:1)
您的三个子查询
select count(distinct clid) from call_log where enteredon = '16-JUL-13')
select count(disconnectflag) from call_log where disconnectflag='IVR' and enteredon = '16-JUL-13'
select count(callerid) from call_log where enteredon = '16-JUL-13')
对于结果集中的每一行,执行完全相同。这就是为什么你看到重复的相同值。
由于你想要分组多个没有相互排斥结果的字段,我会说(这可能不是最好的方法)组对你感兴趣的每个项目,然后结合你的结果。
答案 2 :(得分:1)
试试这个:
Select
c.custsegment,
count(distinct clid) as UniqCalls,
count(callerid) as TotalCalls
from call_log c
inner join
(select count(disconnectflag) as IvrCalls, custsegment
from call_log where disconnectflag='IVR' and enteredon = '16-JUL-13' group by custsegment) t
on c.custsegment=t.custsegment
where enteredon = '16-JUL-13'
group by c.custsegment