MySQL - 计算由其他列排序的列的值

时间:2015-05-16 09:40:43

标签: mysql sql

我想要实现这个表:

|Country|Cars|Blue Cars|Red Cars| Green Cars |
|Mexico | 22 |    12   |   8    |     2      |
|U.S.A  | 12 |    6    |   3    |     3      |
|Denmark| 10 |    3    |   2    |     5      |

从每个汽车生成报告(行)的数据库表中,如下所示:

|Country|car_color|
|Mexico | Blue    |    
|U.S.A  | Red     |    
|Denmark| Blue    | 
|Denmark| Blue    |
|Mexico | Blue    |
|Denmark| Green   |
|Denmark| Red     |
|U.S.A  | Red     |
|Denmark| Green   |

我做了第一部分:将国家/地区分组并按国家/地区获取汽车总数,即此查询:

SELECT country,
       COUNT(county)
FROM my_table
GROUP BY country
ORDER BY COUNT(country)

我的问题是,在按州分组行并获取每个国家的汽车总数后,如何获取第一张表中的彩色汽车列?

注意:我尝试了几种方法,但我未能实现这一目标。举个例子,我用过:

SELECT country,
       COUNT(country),
       COUNT(case when car_color = 'Green' then 1 else 0 end)
FROM my_table
GROUP BY country
ORDER BY COUNT(country)

但是,这只显示了与#34; Green Car"列相同的汽车价值(一个国家的汽车总数)。

请帮忙!

1 个答案:

答案 0 :(得分:2)

COUNT计算非NULL行,而CASE始终返回值。

切换到SUM或省略ELSE部分:

 SELECT country
  ,COUNT(*) AS cars 
  ,SUM(case when car_color = "blue" then 1 else 0 end) AS "blue cars" 
  ,SUM(case when car_color = "red" then 1 else 0 end) AS "red cars"
  ,COUNT(case when car_color = "green" then 1 end) AS "green cars"
FROM my_table 
GROUP BY country 
ORDER BY COUNT(*) DESC