考虑这个样本数据:
+----------+------+--------+-----------------+
| username | qnum | qvalue | date |
+----------+------+--------+-----------------+
| Linda | 1 | 2 | 11/14/2017 7:25 |
+----------+------+--------+-----------------+
| Fred | 1 | 1 | 11/23/2017 7:59 |
+----------+------+--------+-----------------+
| Brian | 5 | 2 | 11/17/2017 7:25 |
+----------+------+--------+-----------------+
| Sandra | 6 | 1 | 11/25/2017 7:26 |
+----------+------+--------+-----------------+
| Tom | 6 | 1 | 11/22/2017 7:32 |
+----------+------+--------+-----------------+
| Paul | 6 | 1 | 11/22/2017 7:36 |
+----------+------+--------+-----------------+
| Andrew | 7 | 2 | 11/23/2017 7:37 |
+----------+------+--------+-----------------+
| Luke | 3 | 1 | 11/23/2017 8:03 |
+----------+------+--------+-----------------+
| William | 8 | 1 | 11/23/2017 8:03 |
+----------+------+--------+-----------------+
| Linda | 9 | 2 | 11/15/2017 8:03 |
+----------+------+--------+-----------------+
| Brian | 3 | 2 | 11/17/2017 8:04 |
+----------+------+--------+-----------------+
| Joan | 9 | 1 | 11/23/2017 8:04 |
+----------+------+--------+-----------------+
| Chris | 8 | 1 | 11/23/2017 8:04 |
+----------+------+--------+-----------------+
| Kim | 8 | 1 | 11/15/2017 8:04 |
+----------+------+--------+-----------------+
我试图让上周获得最高q值的人。我可以使用以下SQL获取此信息,但我的问题是,如果多个用户具有最高分,那么它不会显示它们的名称,因为我使用LIMIT函数。有没有办法一起使用max和sum来获得所需的结果?期望的结果将是Linda和Brian列出的结果集,因为上周他们的总和得分为4并且并列。
SELECT username, SUM(qvalue) AS score FROM trivia_scoreboard
WHERE `date` >= CURDATE() - INTERVAL DAYOFWEEK(CURDATE())+6 DAY AND `date` < CURDATE() - INTERVAL DAYOFWEEK(CURDATE())-1 DAY
GROUP BY username
ORDER BY score DESC
LIMIT 1
答案 0 :(得分:4)
您必须使用一个可以获得所有人总数的查询来加入该查询。
SELECT t1.*
FROM (
SELECT username, SUM(qvalue) AS score FROM trivia_scoreboard
WHERE `date` >= CURDATE() - INTERVAL DAYOFWEEK(CURDATE())+6 DAY AND `date` < CURDATE() - INTERVAL DAYOFWEEK(CURDATE())-1 DAY
GROUP BY username
) AS t1
JOIN (
SELECT SUM(qvalue) AS score FROM trivia_scoreboard
WHERE `date` >= CURDATE() - INTERVAL DAYOFWEEK(CURDATE())+6 DAY AND `date` < CURDATE() - INTERVAL DAYOFWEEK(CURDATE())-1 DAY
GROUP BY username
ORDER BY score DESC
LIMIT 1
) AS t2 ON t1.score = t2.score
答案 1 :(得分:3)
您也可以使用having
:
SELECT ts.username, SUM(ts.qvalue) AS score
FROM trivia_scoreboard fs
WHERE ts.`date` >= CURDATE() - INTERVAL DAYOFWEEK(CURDATE())+6 DAY AND
ts.`date` < CURDATE() - INTERVAL DAYOFWEEK(CURDATE())-1 DAY
GROUP BY username
HAVING score = (SELECT SUM(ts2.qvalue) as score
FROM trivia_scoreboard ts2
WHERE ts2.`date` >= CURDATE() - INTERVAL DAYOFWEEK(CURDATE())+6 DAY AND
ts2.`date` < CURDATE() - INTERVAL DAYOFWEEK(CURDATE())-1 DAY
GROUP BY username
ORDER BY score DESC
LIMIT 1
);
这与使用join
的版本之间的区别实际上是一个品味问题。由于有关聚合如何在更大量的数据上扩展的详细信息,这可能会有更好的性能。