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
不起作用以及如何选择具有此条件的行?
答案 0 :(得分:1)
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