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


RESULT IS:

field_name    count 

AAA              9
BBB              0
CCC              7

但是我怎样才能只得到第二列中超过 0 的行。

4

3 回答 3

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

于 2013-05-14T04:46:17.750 回答
1

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
于 2013-05-14T04:48:59.563 回答
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因此您可以处理聚合函数

于 2013-05-14T04:45:57.933 回答