简体   繁体   中英

Using DISTINCT, COUNT and HAVING in a MySQL Query

I want to count all players that have a sum of at least 300 points after a given date. I have this:

SELECT
    COUNT(DISTINCT playerID)
FROM
    table
WHERE
    game_date > '$date'
HAVING
    SUM(points) >= 300

Which is counting also the players that have a sum of less than 300 points. How can I solve this?

As pointed out by Andre Bossard:

To get the list of all players with points>=300:

SELECT * FROM (SELECT playerID, SUM(points) points FROM table WHERE game_date>'$date' GROUP BY playerID) a WHERE points>=300

To get the count:

SELECT COUNT(*) FROM (SELECT playerID, SUM(points) points FROM table WHERE game_date>'$date' GROUP BY playerID) a WHERE points>=300

Use a subquery for that:

SELECT COUNT(*) FROM
(
  SELECT playerID, SUM(points) AS `total`
  FROM `table`
  WHERE game_date > '$date'
  GROUP BY playerID
) tmp
WHERE total>=300

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