2011-03-19 55 views
0

我想查詢使用連接表,但我不能讓這裏成功我的表如何獲得多個最大列值的MySQL

Score 
id , user_id ,  score , week 
1  , 123  ,  2  , 1 
2  , 432  ,  2  , 1 
3  , 432  ,  3  , 1 
4  , 123  ,  2  , 2 

我想在總和的基礎查詢前二十名的用戶記錄周1和第2周的最大總

我想要的結果應該是

id  , user_id  , week1score , week2score 
1  , 123  , 2   , 2 
2  , 432  , 3   , 0 

的公式是爲了通過降總和(MAX(week1)+ MAX(week2))

感謝 伊納姆

回答

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 

您需要在下列的組合大指數

  • (USER_ID,一週,評分)
+0

有一個星期可以得到多個記錄像第一週的問題可能有兩個相同的用戶得分,現在是2,3必須選擇的最高分是3 – 2011-03-19 13:08:12

+0

我想按用戶在第1周的最大記錄數+第2周的用戶最大記錄數之和來訂購。如此總和(max(week1)+ max(week2) )) – 2011-03-19 13:09:36

+0

你是真棒男人它工作只有一件事缺少,你使用SUM(分數)命令我想命令它作爲總和(week1score + week2score)我怎麼能做到這一點? – 2011-03-19 13:13:49