这是我2个月的sql表的简化版本(ORDERED BY DATE):
player_id | 日期| 得分
1 2011-05-25 1200
2 2011-05-25 3400
3 2011-05-26 3200
4 2011-05-26 4400
1 2011-05-28 1000
2 2011-05-28 2000
3 2011-05-29 3000
4 2011-05-29 4000
1 2011-06-24 1300
2 2011-06-24 2500
3 2011-06-24 5000
4 2011-06-24 3000
基本上,我想要一个查询,显示特定月份/特定年份中所有玩家的最后得分。
示例:
如果我想要05个月中所有球员的最终得分,那么结果 将是:
1 2011-05-28 1000
2 2011-05-28 2000
3 2011-05-29 3000
4 2011-05-29 4000
到目前为止我的sql查询:
SELECT m1.* FROM table m1
LEFT JOIN table m2 ON (m1.player_id = m2.player_id AND m1.date < m2.date)
WHERE m2.date IS NULL
AND month(m1.date) = 05
AND year(m1.date) = 2011
ORDER BY score DESC);
这似乎并没有显示所有玩家,只有在05年后没有玩过的玩家。我在哪里添加日期选择?
先谢谢!
**编辑 对于我来说,约翰·斯特里亚托克的答案对我来说很有用:)
答案 0 :(得分:2)
我认为他指的是这里显示的技术:Retrieving the last record in each group
附加约束条件是他不想要最后一条记录,而是一个月内的最后一条记录。
奇怪的是,你必须两次提供额外的约束,一旦处于连接条件,再次过滤结果。这应该为你做。
SELECT m1.* FROM table m1
LEFT JOIN table m2 ON
(m1.player_id = m2.player_id AND m1.date < m2.date
AND m2.date < '2011-06-01')
WHERE m2.date IS NULL AND month(m1.date) = 5 AND year(m1.date) = 2011
答案 1 :(得分:0)
假设唯一的(player_id, date)
组合:
SELECT
t.*
FROM
TableX AS t
JOIN
( SELECT
player_id
, MAX(date) AS maxDate
FROM
TableX
WHERE
date BETWEEN '2011-05-01'
AND LAST_DAY('2011-05-01')
GROUP BY
player_id
) AS tg
ON
(tg.player_id, tg.maxDate) = (t.player_id, t.date)
ORDER BY
t.score DESC