简体   繁体   中英

mysql possible to select count(distinct(id) where col = 'value')?

I'm using car makes as an example, which fits my situation nicely.

Example query I have now, that gives a simple count per state:

SELECT
  state as State,
  count(distinct(idnumber)) as Total
FROM
  database.table
WHERE
  make IN('honda', 'toyota', 'subaru')
GROUP BY
  state
ORDER BY
  state

Note that this would give me the count for each of the car makes, excluding things like Ford, Chevy, etc. The list of makes would be every make.

Is there a way I can break that down to give me the count of each make by state without resorting to a sub-query? In my head it would be like having a where statement in the count(distinct(idnumber)) select, but I'm not sure that's possible.

Here's what is in my head:

SELECT
  state as State,
  count(distinct(idnumber)) as Total_State,
  (count(distinct(idnumber)) WHERE make = 'honda') as Total_Honda
WHERE
  make IN('honda', 'toyota', 'subaru')
GROUP BY
  state
ORDER BY
  state

You could add multiple columns to your group by:

GROUP BY
  state, make

I may misunderstand your question, but you can group along two columns, so you will get the number of fords made in CA and hondas made in CA etc

To be explicit, your query would be this:

SELECT
  state as State,
  count(distinct(idnumber)) as Total,
  make as Make
FROM
  database.table
WHERE
  make IN('honda', 'toyota', 'subaru')
GROUP BY
  state, make
ORDER BY
  state

Just as a fun test, I did this:

create table `cars` (
`id` int(11),
`make` varchar(255),
`state` varchar(255)
);


insert into cars(id, make, state) values 
     (1, 'honda', 'ca'), (2, 'honda', 'ca'), (3, 'toyota', 'ca'), 
     (4, 'toyota', 'az'), (5, 'toyota', 'az'), (6, 'honda', 'az');


SELECT state as State, count(id) as Total, make as Make
FROM cars
WHERE make IN('honda', 'toyota', 'subaru')
GROUP BY state, make
ORDER BY state

And got back:

+-------+-------+--------+
| State | Total | Make   |
+-------+-------+--------+
| az    |     1 | honda  |
| az    |     2 | toyota |
| ca    |     2 | honda  |
| ca    |     1 | toyota |
+-------+-------+--------+

Which is what I expected. Is that what you were thinking?

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