我有一个关于SUM
的问题
表:
ID date type price limit
1 01/02/2016 1 10 3
2 02/02/2016 1 15 2
3 03/02/2016 1 10 0
4 01/02/2016 2 10 2
5 02/02/2016 2 20 2
6 03/02/2016 2 30 2
$sql = SELECT type,SUM(price) as total from table **where limit>0** GROUP BY type
通常会返回:
1 35
2 60
但我需要,如果类型1有任何零限制不计算。
***2 60***
我需要使用子查询吗?
最佳答案
试试这个:
SELECT `type`, SUM(price) AS total
FROM table
GROUP BY `type`
HAVING COUNT(CASE WHEN `limit` = 0 THEN 1 END) = 0
HAVING
子句将过滤掉至少包含 1 个 limit=0
行的任何 type
组。
关于mysql - 子查询示例帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35138587/