在mysql中选择多个计数

时间:2011-05-30 06:18:15

标签: mysql sql aggregate-functions

MySQL可以做这样的事情:

SELECT COUNT(*) as totalcount, 
       COUNT(*) WHERE foo IS NULL as conditional_count 
  FROM baz

即。在单个选择中获取两个计数,一个是一切,以及一个匹配WHERE子句的东西吗?

5 个答案:

答案 0 :(得分:11)

如果你的数据库支持CASE WHEN语句,这将有效,否则你仍然会得到基本的想法。

SELECT COUNT(*), 
       SUM(CASE WHEN FOO IS NULL THEN 1 ELSE 0 END) AS COUNT_CONDITIONAL
  FROM baz

答案 1 :(得分:2)

它应该像这样SELECT COUNT(*) as totalcount, (SELECT COUNT(*) WHERE foo IS NULL) as conditional_count FROM baz这是一个单一的查询,但在

中有子查询

答案 2 :(得分:1)

SELECT count()为totalcount, (选择COUNT()FROM baz WHERE foo IS NULL) as conditional_count FROM baz;

我不能在计数括号之间放置星号(*)! 我说,但我无法显示它。

答案 3 :(得分:0)

尝试使用UNION(未测试)

SELECT COUNT(*) as totalcount FROM baz
UNION
SELECT  COUNT(*) WHERE foo IS NULL as conditional_count FROM baz

答案 4 :(得分:-1)

我不认为这是可能的。我估计你需要两个查询。

Select count(*) from baz

Select count(foo) from baz where foo is null