将2个计数查询合并为1个

时间:2019-02-07 09:35:15

标签: mysql

无法获得每个帐户代码的总和,它给了我所有的总和,这是代码

SELECT cdr.accountcode,
(SELECT COUNT(id)  FROM cdr WHERE cdr.calldate > now() - INTERVAL 30 MINUTE and cdr.dstchannel LIKE '%neural%') AS callcount , 
(SELECT COUNT(id)  FROM cdr WHERE cdr.calldate > now() - INTERVAL 3 MINUTE and cdr.dstchannel LIKE '%neotel%')  AS localcallcount
FROM cdr

表结构

id | calldate   | clid  | src | dst             | dstchannel | accountcode | note
---+------------+-------+-----+-----------------+------------+-------------+------
12 | 2018-12-05 | "105" | 105 | SIP/neotel/1234 | 1234user   | testuser    | null

预期产量

  

帐户代码电话号码本地电话号码

     

5000user 1 2
  5236用户1 3

1 个答案:

答案 0 :(得分:0)

使用SUM()代替COUNT()COUNT()不管发生什么,每一行都很重要。 SUM()函数中的布尔表达式返回1或0,具体取决于它是true还是false。

SELECT cdr.accountcode,
SUM(cdr.calldate > now() - INTERVAL 30 MINUTE and cdr.dstchannel LIKE '%neural%') AS callcount , 
SUM(cdr.calldate > now() - INTERVAL 3 MINUTE and cdr.dstchannel LIKE '%neotel%')  AS localcallcount
FROM cdr