基于WHERE的多个聚合查询

时间:2013-09-22 05:52:45

标签: mysql group-by

这可能是超级简单的...... 但是现在我无法想到如何在一个声明中做到这一点。

我知道我可以SELECT count(id)WHERE status = APP,并重复所有计数。但我想在一个查询中完成它。 我会按城市分组然后按状态分组,并且Sum?

表格如下......

City  |  Status  |  
City 1    APP
City 1    NH
City 1    APP
City 1    NEW
City 2    NEW
City 2    APP
City 2    APP
City 2    NH

我想返回以下数组。

 {[cityname]=>City1,[Total]=>4,[APP]=>1,[NH]=>1,[NEW]=>2}, 
 {[cityname]=>City2,[Total]=>4,[APP]=>2,[NH]=>1,[NEW]=>1}

我目前的疑问是......

 SELECT COUNT(id) as total, city WHERE status = 'APP' GROUP BY city
 SELECT COUNT(id) as total, city WHERE status = 'NH' GROUP BY city
 SELECT COUNT(id) as total, city WHERE status = 'NEW' GROUP BY city

我知道这非常简单,但已经有一段时间了,我忘记了如何将这些结合成一个陈述。

3 个答案:

答案 0 :(得分:2)

您也可以按城市和状态进行分组

SELECT COUNT(id) as total, city, status  GROUP BY city, status

答案 1 :(得分:2)

如果您想要每个城市的行APPNHNEW为列,您可以像这样使用条件SUM()

SELECT city,
       COUNT(*) total, 
       SUM(CASE WHEN status = 'APP' THEN 1 ELSE 0 END) app,
       SUM(CASE WHEN status = 'NH'  THEN 1 ELSE 0 END) nh,
       SUM(CASE WHEN status = 'NEW' THEN 1 ELSE 0 END) new
  FROM table1
 GROUP BY city

输出:

|   CITY | TOTAL | APP | NH | NEW |
|--------|-------|-----|----|-----|
| City 1 |     4 |   2 |  1 |   1 |
| City 2 |     4 |   2 |  1 |   1 |

这是 SQLFiddle 演示

答案 2 :(得分:0)

这是一种只适用于MySQL

的速记方法
SELECT City,
       COUNT(*) Total, 
       SUM(Status = 'APP') APP,
       SUM(Status = 'NH') NH,
       SUM(Status = 'NEW') `NEW`
FROM   TableName
GROUP  BY City