简体   繁体   中英

mysql address outer query from subquery

I have this query:

SELECT 
    sec_to_time(avg(t1.sessiontime)) as aloc,
    CONCAT(TRUNCATE(sum(t1.terminatecauseid = 1) * 100 / count(*),
                1),
            '%') as asr,
    count(*) as calls,
    cast(t1.destination as unsigned) as prefix,
    t2.destination as destination,
    SEC_TO_TIME(sum(t1.sessiontime)) as duration
FROM
    cc_call AS t1
        inner join
    cc_prefix as t2 ON t1.destination = t2.prefix
WHERE
    t1.card_id = '133' AND t1.starttime >= ('2014-06-1') AND t1.starttime <= ('2014-07-01 23:59:59') and t1.terminatecauseid = 1
group by t1.destination
order by duration DESC
LIMIT 0 , 25

t1.terminatecauseid = 1 means successful call, 'asr' means average success rate,

Im trying to find out how many calls with (t1.terminatecauseid = 1) from the total calls made to an extension.

this line doesn't work:

sum(t1.terminatecauseid = 1) * 100 / count(*)

since I already have (t1.terminatecauseid = 1) in the WHERE clause.

Im thinking about putting a subquery, to retrieve total calls, where count(*) currently is.

How can I have this query calculate the ASR with total calls made?

example sqlfiddle

if possible, I'd like to not show results with duration=NULL

Use conditional aggregation, something like this:

SELECT sec_to_time(avg(case when t1.terminatecauseid = 1 then t1.sessiontime end)) as aloc,
       CONCAT(TRUNCATE(sum(t1.terminatecauseid = 1) * 100 / count(*),
               1),
             '%') as asr,
       count(*) as TotalCalls,
       sum(t1.terminatecauseid = 1) as Terminated1Calls,
       cast(t1.destination as unsigned) as prefix,
       t2.destination as destination,
       SEC_TO_TIME(sum(case when t1.terminatecauseid = 1 then t1.sessiontime end)) as duration
FROM cc_call t1 inner join
     cc_prefix t2
     ON t1.destination = t2.prefix
WHERE t1.card_id = '133' AND
      t1.starttime >= ('2014-06-1') AND t1.starttime <= ('2014-07-01 23:59:59') 
group by t1.destination
order by duration DESC
LIMIT 0 , 25;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM