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的行。
答案 0 :(得分:3)
使用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
分组
答案 1 :(得分:1)
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
之后执行,因此您可以解决聚合函数
答案 2 :(得分:1)
尝试以下。
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
实际上,第二个查询很好理解,但第一个查询更好:)
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