SELECT field_name,
SUM(CASE WHEN field_name is not null THEN 1 ELSE 0 END) as count from table_name group by department
RESULT IS:
field_name count
AAA 9
BBB 0
CCC 7
但是我怎样才能只得到第二列中超过 0 的行。
使用HAVING
条款:
SELECT field_name,
SUM(CASE WHEN field_name IS NOT NULL
THEN 1 ELSE 0 END) AS `count`
FROM table_name
GROUP BY department
HAVING `count` > 0
我认为你正在选择department
而不是field_name
或者你需要分组field_name
try belows.
SELECT field_name, SUM(CASE WHEN field_name is not null THEN 1 ELSE 0 END) as count
from table_name
where field_name is not null
actually, second query is good to understand, but first query is better :)
SELECT field_name, SUM(CASE WHEN field_name is not null THEN 1 ELSE 0 END) as count
from table_name
where SUM(CASE WHEN field_name is not null THEN 1 ELSE 0 END) > 0
SELECT field_name,
SUM(CASE WHEN field_name is not null
THEN 1
ELSE 0
END) as count
from table_name
group by department
HAVING `count` > 0
HAVING
子句在之后 WHERE
执行,GROUP BY
因此您可以处理聚合函数