我需要从下表中获取max lesson_score,以及特定用户的相应日期:
--------------------------------
|uid |lesson_score |date |
--------------------------------
|1 |2 |1391023460 |
|1 |8 |1391023518 |
|1 |4 |1391023596 |
--------------------------------
我需要一个结果:
---------------------------
|lesson_score |date |
---------------------------
|8 |1391023596 |
---------------------------
我的SQL看起来像这样:
SELECT date, MAX(lesson_score) AS lesson_score
FROM cdu_user_session_progress
WHERE uid = 1
GROUP BY date";
但它只给了我三行:
---------------------------
|lesson_score |date |
---------------------------
|2 |1391023460 |
|4 |1391023596 |
|8 |1391023518 |
---------------------------
我做错了什么?谢谢!
答案 0 :(得分:2)
SELECT date, MAX(lesson_score) AS lesson_score
FROM cdu_user_session_progress
WHERE uid = 1
GROUP BY date";
MAX是一个聚合函数,如果有多个lesson_score值,它将返回lesson_score的最大值
在您的查询中,值始终相同,因此返回该值。请记住,SELECT MAX(...)不能对整个表记录起作用,它会逐个处理每个记录。
您可以使用此顺序获取结果
SELECT top 1 date, lesson_score AS lesson_score
FROM cdu_user_session_progress
WHERE uid = 1
ORDER BY lesson_score DESC;
答案 1 :(得分:1)
尝试使用
SELECT lesson_score, date FROM cdu_user_session_progress ORDER BY lesson_score DESC LIMIT 1;
ORDER BY
- 部分负责,最多。 lession_score将在开头提取。
在订购之后,您会得到以下结果:
---------------------------
|lesson_score |date |
---------------------------
|8 |1391023518 |
|4 |1391023596 |
|2 |1391023460 |
---------------------------
现在LIMIT
- 部分说,数据库应该只返回第一行 - 所有其他结果行将被忽略,结果如下:
---------------------------
|lesson_score |date |
---------------------------
|8 |1391023518 |
---------------------------
为了获得最低分,你只需写ASC
DESC
的整数(或删除它,因为ASC
是默认值)
答案 2 :(得分:0)
为什么你想要这个小组?只需在您的查询中使用Order BY ColumnName DESC LIMIT 1
,它就会返回所有记录,因为UID=1
对所有记录都是真的,只是按日期对其进行分组,每个MAX
显示DATE
答案 3 :(得分:0)
SELECT [date], lesson_score
FROM cdu_user_session_progress
WHERE lesson_score = (SELECT MAX(lesson_score) FROM cdu_user_session_progress GROUP BY [ui] HAVING [uid] = 1)
AND [uid] =1;