我正在尝试使用join查询表,但我无法在这里获得成功
Score
id , user_id , score , week
1 , 123 , 2 , 1
2 , 432 , 2 , 1
3 , 432 , 3 , 1
4 , 123 , 2 , 2
我想在第1周和第2周的最大总和之和的基础上查询前20位用户记录
我希望结果应该是
id , user_id , week1score , week2score
1 , 123 , 2 , 2
2 , 432 , 3 , 0
公式是降序和(max(week1)+ max(week2))
的顺序由于 INAM
答案 0 :(得分:1)
这样的事情
SELECT t1.user_id,
SUM(week1score) AS week1score,
SUM(week2score) AS week2score
FROM (SELECT user_id
FROM `table`
GROUP BY user_id) AS t1
JOIN (SELECT user_id,
Max(IF(`week` = 1, score, 0)) AS week1score,
Max(IF(`week` = 2, score, 0)) AS week2score
FROM `table`
GROUP BY user_id,
`week`) t2
ON t2.user_id = t1.user_id
GROUP BY user_id
ORDER BY ( SUM(week1score) + SUM(week2score) ) DESC
您需要以下列的复合索引