简体   繁体   中英

MySQL - Count values of a column ordered by other column

I want to achieve this table:


|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      |

That from a database table that makes a report (row) for every car, like this:

|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   |

I did the first part: grouping the countries and get the total number of cars by country, that was with this query:

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

My question is, how do I get the color car columns in the first table after grouping the rows by county and getting the total number of cars by every country?

Note: I tried several ways but I'm failing to achieve this. As an example, I used:

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)

But that only shows the same value of Cars (total number of cars in a country) for the column "Green Car".

Help please!

COUNT counts non-NULL rows and your CASE always returns a value.

Either switch to SUM or omit the ELSE part:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM