我有一张数据表:
id | name | userid | score | date |
--------------------------------------------------------
1 | john | 4 | 233 | 2014-02-02
2 | mary | 5 | 1256 | 2013-02-05
3 | john | 6 | 100 | 2013-03-08
4 | elvis | 7 | 123 | 2013-03-04
5 | john | 2 | 1234 | 2013-03-02
我想显示上个月的每周高分详情。周日从周日开始。每周最多显示4位得分者。我的数据将以json格式输出。
目前我的查询输出仅显示上周的结果。
"weekly_winners":[
{
"id":"2",
"score":"1256"
},
{
"id":"1",
"score":"233"
}
],
但我想表现出像
"weekly_winners":[
"week":"1"
[
{
"id":"2",
"score":"1256"
},
{
"id":"1",
"score":"233"
}
],
"week":"2"
[
{
"id":"2",
"score":"1256"
},
{
"id":"1",
"score":"233"
}
],
],
我目前的查询是:
SELECT winner.id,winner.score
FROM `winner` AS winner
WHERE winner.date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND winner.date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
ORDER BY winner.score DESC
LIMIT 4
答案 0 :(得分:1)
您可以使用YEARWEEK()
命令进行分组。将星期日作为一周的开始,请参阅此post。
因此,您可以使用:YEARWEEK(winner.date, 0)
来指定周。
至于按组选择前N行,我在执行此操作时发现的最佳参考是here。向下滚动到以下部分:
从每个组中选择前N行
我过去曾用这篇文章来解决这个问题。
*注意:YEARWEEK()
将处理新的一年,将所有日期都指定为指定日期,开始新一周到上一年的最后一周......正如您/应该期望的那样。
修改强>
这是一个可能的查询(选择前两个以避免为小提琴示例输入一堆数据):
SELECT winner.id,winner.score, YEARWEEK(winner.date, 0)
FROM `winner` AS winner
WHERE (
SELECT count(*)
FROM winner as w
WHERE YEARWEEK(w.date, 0) = YEARWEEK(winner.date, 0)
AND w.score >= winner.score
) <= 2;