这是我 2 个月的 sql 表的简化版本(按日期排序):
player_id | date | score
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
基本上,我想要一个显示所有玩家在特定月份/特定年份的最后得分的查询。
例子:
If I want the final scores of all players in the month 05, te result would be:
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 之后几个月没有玩过的玩家。我在哪里添加日期选择?
**编辑 John Nestoriak 的回答对我有用:)
最佳答案
我认为他指的是这里显示的技术: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
关于php - 我想要特定月份+年份的所有玩家的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9121008/