查询多个计数语句

时间:2012-12-17 18:44:50

标签: mysql sql

我想结合以下两个查询,以便最终得到三列:RelativePath,field = null /空字符串,带有值的字段。我可以单独执行查询,但是我在组合它们时遇到了问题。

SELECT RELATIVEPATH, COUNT(RELATIVEPATH) FROM APP 
       WHERE (FIELD IS NULL) OR (FIELD = '')
       GROUP BY (RELATIVEPATH);

SELECT RELATIVEPATH, COUNT(RELATIVEPATH) FROM APP
       WHERE (FIELD IS NOT NULL) 
       GROUP BY (RELATIVEPATH);

1 个答案:

答案 0 :(得分:7)

您需要case声明:

SELECT RELATIVEPATH, sum(case when (FIELD IS NULL) OR (FIELD = '') then 1 else 0 end),
       sum(case when field is not null then 1 else 0 end)
FROM APP 
GROUP BY (RELATIVEPATH);

这假设count(RelativePath)的意图是计算所有行。如果您真的想要计算列的非NULL值,可以使用:

SELECT RELATIVEPATH, count(case when (FIELD IS NULL) OR (FIELD = '') then RelativePath end),
       count(case when field is not null then RelativePath end)
FROM APP 
GROUP BY (RELATIVEPATH);