[英]mysql having clause on sum of count
I have a following query giving following result 我有以下查询,给出以下结果
SELECT ttable.*
FROM ( SELECT
`STATUS`,
`TELCOID`,
COUNT(*) smsCount
FROM `smsout`
WHERE `STATUS` = 'Send'
AND (RECEIVEDTIME BETWEEN DATE_SUB(NOW(), INTERVAL 1000000 MINUTE) AND NOW())
GROUP BY `STATUS` , `TELCOID`
) ttable
#having Sum(smscount) > 2500 ;
STATUS TELCOID smsCount
send -3 2
send -1 2487
send 158 233
send 162 16
what I needed is to add a where/having clause which will check sum(smscount) >2500 then return the result set other wise nothing What can i change in this query to achieve it. 我需要添加一个where / having子句,该子句将检查sum(smscount)> 2500,然后以其他方式返回结果集,什么也没做,我可以在此查询中进行哪些更改以实现此目的。 In the current result sum of 2 + 2487 + 233 + 16 is greater then 2500 so it will not return any thing.
在当前结果中,2 + 2487 + 233 + 16的总和大于2500,因此它不会返回任何东西。 if instead of 2500 i place 3000 then resultset will return
如果代替2500我放置3000,那么结果集将返回
You either need to run two queries or use variables. 您需要运行两个查询或使用变量。 I think this might work:
我认为这可能有效:
SELECT status, telcoid, smscount
FROM (SELECT `STATUS`, `TELCOID`, COUNT(*) as smsCount,
(@s := @s + COUNT(*)) as cumesum
FROM `smsout` CROSS JOIN (SELECT @s := 0) vars
WHERE `STATUS` = 'Send' AND
RECEIVEDTIME BETWEEN DATE_SUB(NOW(), INTERVAL 1000000 MINUTEAND NOW())
GROUP BY `STATUS` , `TELCOID`
) ttable
WHERE @s > 2500;
Sometimes variables don't work quite right with aggregation, so you might need an extra layer of subqueries for this to work. 有时变量不能很好地与聚合配合使用,因此您可能需要额外的子查询层才能使其起作用。
EDIT: 编辑:
Try this version: 试试这个版本:
SELECT status, telcoid, smscount
FROM (SELECT t.*, (@s := @s + COUNT(*)) as cumesum
FROM (SELECT `STATUS`, `TELCOID`, COUNT(*) as smsCount
FROM `smsout`
WHERE `STATUS` = 'Send' AND
RECEIVEDTIME BETWEEN DATE_SUB(NOW(), INTERVAL 1000000 MINUTEAND NOW())
GROUP BY `STATUS` , `TELCOID`
) t CROSS JOIN
(SELECT @s := 0) vars
) t
WHERE @s > 2500;
smscount is a sum because you wrote count(*) smscount smscount是一笔款项,因为您写了count(*)smscount
can you try 你能试一下吗
SELECT ttable.*
FROM ( SELECT
`STATUS`,
`TELCOID`,
COUNT(*) smsCount
FROM `smsout`
WHERE `STATUS` = 'Send'
AND (RECEIVEDTIME BETWEEN DATE_SUB(NOW(), INTERVAL 1000000 MINUTE) AND NOW())
GROUP BY `STATUS` , `TELCOID`
) ttable
having smscount > 2500 ;
SELECT `STATUS`, `TELCOID`, COUNT(*) smsCount
FROM `smsout`
WHERE `STATUS` = 'Send'
AND (RECEIVEDTIME BETWEEN DATE_SUB(NOW(), INTERVAL 1000000 MINUTE) AND NOW())
GROUP BY `STATUS` , `TELCOID`
HAVING COUNT(*) > 2500;
The subquery shouldn't be necessary. 子查询应该不是必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.