0

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

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

表如下......

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

我知道这非常简单,但是已经有一段时间了,我忘记了如何将它们准确地组合成一个语句。

4

3 回答 3

2

If you want a row per city with APP, NH, NEW being columns you can use conditional SUM() like this

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

Output:

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

Here is SQLFiddle demo

于 2013-09-22T06:05:12.097 回答
2

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

SELECT COUNT(id) as total, city, status  GROUP BY city, status
于 2013-09-22T06:01:24.410 回答
0

这是一种仅适用于MySQL

SELECT City,
       COUNT(*) Total, 
       SUM(Status = 'APP') APP,
       SUM(Status = 'NH') NH,
       SUM(Status = 'NEW') `NEW`
FROM   TableName
GROUP  BY City
于 2013-09-22T07:57:23.157 回答