在postgres中以不同列的输出结合

时间:2016-12-27 13:51:45

标签: mysql sql-server postgresql

我正在为拨号公司工作,我们有一个呼叫历史记录表,其中我们有不同的列。

现在我想要一个可以计算的输出:

已连接的外拨电话总数

Select count(*) 
from call_history 
where system_disposition = 'CONNECTED'   

系统检测到的总AMD

Select count(*) 
from call_history 
system_disposition='CONNECTED' and call_id in (
    select call_id 
    from udh 
    where disposition_code = 'Answering machine'
)

AGent检测到的总AMD

R.id.text1

现在,如果我使用union命令,所有结果都会出现在一列中并且使用交叉连接会给出重复输出,即限制2给出每个条目的输出两次。

请帮我制作一个可以告诉我的查询:

总出站连接数| AMD by SYSTEM | AMD by AGent |泄漏为(AMD代理/(总计)

2 个答案:

答案 0 :(得分:0)

您可以将结果合并,并在单个列中选择每个结果,如下所示:

Select sum(r1) as result1, sum(r2) as redult2, sum(r3) as result3 from(
Select count(*) as r1, 0 as r2,0 as r3 from call_history where system_disposition='CONNECTED' and call_type='OUTBOUND'
Union
Select 0 as r1,count(*) as r2, 0 as r3 from call_history where system_disposition='CONNECTED')
Union
Select 0 as r1, 0 as r2,count(*) as r3 from call_history system_disposition='CONNECTED' and call_id in (select call_id from udh where disposition_code='Answering machine')
)

答案 1 :(得分:0)

对于Postgresql

select *, "AMD by AGent"::numeric/"Total outbound conected" as "Leakage"
from (
    select
        count(call_type = 'OUTBOUND' or null) as "Total outbound conected",
        count(*) as "AMD by SYSTEM",
        count(exists (
            select 1
            from udh
            where
                disposition_code = 'Answering machine' and
                call_id = call_history.call_id
        ) or null) as "AMD by AGent"
    from call_history
    where system_disposition = 'CONNECTED'
) s

在9.4+中有aggregate filter