简体   繁体   中英

SELECT count of multiple columns with a WHERE clause

I am trying to count statistics of 2 given columns but I want to write multiple counts in the same query for the given statistic. How can I accomplish this?

Here is my code, to give you more of an idea of what I am trying to do

SELECT
  COUNT(DISTINCT `stats`.`rank` + `stats`.`level`) as `bronze`
FROM `stats`
  WHERE `stats`.`rank` = 1 AND `stats`.`level` = 30;

The problem is, I want to have multiple WHERE clauses in one statement which correspond to a given AS. Something along the lines of

SELECT
  COUNT(DISTINCT `stats`.`rank` + `stats`.`level`) as `bronze`,
  COUNT(DISTINCT `stats`.`rank` + `stats`.`level`) as `silver`
FROM `stats`
  WHERE `stats`.`rank` = 1 AND `stats`.`level` = 30 ... as bronze,
        `stats`.`rank` = 2 AND `stats`.`level` = 45 ... as silver ... etc

How would I accomplish this?

Use conditional aggregation with a CASE expression, something along these lines:

SELECT
    some_id,
    COUNT(CASE WHEN rank = 1 AND level = 30 THEN 1 END) AS bronze,
    COUNT(CASE WHEN rank = 2 AND level = 45 THEN 1 END) AS silver
FROM stats
GROUP BY some_id;

If you really want to take a tally over the entire table, then you don't need to use GROUP BY .

I am guessing that you do not want count(distinct) . Instead, I think you just want count() . If so, MySQL has a convenient shortcut:

SELECT SUM( s.rank = 1 AND s.level = 30) as bronze,
       SUM( s.rank = 1 AND s.level = 45) as silver,
       . . .
FROM stats s
WHERE (s.rank, s.level) IN ( (1, 30), (2, 45) );

This also uses the tuple form of IN , which is a nice convenience.

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