--------------------------------
|uid |lesson_score |date |
--------------------------------
|1 |2 |1391023460 |
|1 |4 |1391023518 |
|2 |3 |1391023557 |
|1 |8 |1391023596 |
--------------------------------
如何确定特定用户的最高和最低分数及其各自的日期?
到目前为止,我有这个:
SELECT MAX(lesson_score) AS max_lesson_score, MIN(lesson_score) AS min_lesson_score, date
FROM user_progress
WHERE uid = 1
我需要得到的是:
min: 2, 1391023460
max: 8, 1391023460
我知道它正在返回正确的最低和最高分数,但它只返回一个日期,我甚至不确定它的返回日期......
谢谢!
答案 0 :(得分:0)
您的查询不是合法的SQL,正是因为MIN和MAX得分有不同的数据值。
查询并不简单,因为您希望在不同的行中返回MIN和MAX。
SELECT lesson_score, date
FROM user_progress
WHERE uid = 1
AND (
lesson_score = (SELECT MAX(lesson_score)
FROM user_progress
WHERE uid = 1)
OR (lesson_score = (SELECT MIN(lesson_score)
FROM user_progress
WHERE uid = 1)
)
如果你有多个lesson_score等于MIN或MAX,你会得到额外的行显示它。
答案 1 :(得分:-2)
快速修复:
SELECT MAX(lesson_score) AS max_lesson_score, MIN(lesson_score) AS min_lesson_score, date
FROM user_progress
WHERE uid = 1
GROUP BY date
每当你有一个聚合函数(sum,count,max,min)时,你需要在GROUP BY中包含所有非聚合列,因此它知道在哪些列上执行这些函数。我希望这是有道理的。