0

我有这个查询,我必须计算多个字段

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 CUTSEGMENT 相同的值,我也不确定这是否是计算它的正确方法。请建议。

4

3 回答 3

3

我想你的意思是group bycustsegment。这也使您的查询更简单一些,因为您不需要子选择。

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计算所有非空值,因此您可以为此使用 case(甚至可以省略else null)。或者你可以使用sum也常用的。

于 2013-07-22T19:25:39.943 回答
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')

对于结果集中的每一行,完全按照他们编写的方式执行。这就是为什么您会看到重复的相同值。

由于您想对多个不具有互斥结果的字段进行分组,我会说(这可能不是最好的方法)对您感兴趣的每个项目进行分组,然后组合您的结果.

于 2013-07-22T19:22:37.183 回答
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
于 2013-07-22T19:35:10.937 回答