SELECT
t1.user_id,
count(*) total,
sum(case when t1.var1 = 'yes' then 1 else 0 end) as type1,
sum(case when t1.var1 = 'no' then 1 else 0 end) as type2
FROM table as t1
WHERE type1 > 0
GROUP by t1.user_id
ORDER by type1 DESC
LIMIT 100
结果我得到行:
user_id total type1 type2
1 100 80 20
4 120 70 50
6 90 0 90
请告诉我为什么条件 WHERE type1 > 0
不起作用以及如何选择具有此条件的行?
最佳答案
WHERE
仅适用于原始值,不适用于您刚刚通过汇总其他值而生成的变量,您可以使用 HAVING
来实现此目的:
SELECT
t1.user_id,
count(*) total,
sum(case when t1.var1 = 'yes' then 1 else 0 end) as type1,
sum(case when t1.var1 = 'no' then 1 else 0 end) as type2
FROM table as t1
GROUP by t1.user_id
HAVING type1 > 0
ORDER by type1 DESC
LIMIT 100
请参阅此处使用 HAVING
的另一个示例:http://www.w3schools.com/sql/sql_having.asp
关于mysql - 为什么条件where不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36370852/