2014-12-09 148 views
0

我想創建一個數據庫視圖。我有一張表,其中包含有關人民的記錄,這些記錄在一年中解決了一些合乎邏輯的例子,並且他們得到了相應的分數。從數據庫中選擇多個top3

我需要從SQL查詢創建視圖,但我遇到了一個問題 - 我需要通過一個查詢每年獲得TOP 3用戶。

SELECT solver, year, SUM(points) as TotalPoints 
FROM solving 
GROUP BY solver, year 
ORDER BY year, TotalPoints DESC 

我得到的解算器每年按點和年排序。我知道我需要使用限制,但我也知道我需要一個選擇更多,但我不知道在哪裏。

回答

0

有幾種方法可以在MySQL中解決這個問題。可能效率最高的是使用變量。下面列舉的值:

SELECT yt.*, 
     (@rn := if(@y = year, @rn + 1, 
        if(@y := year, 1, 1) 
       ) 
     ) as seqnum 
FROM (SELECT solver, year, SUM(points) as TotalPoints 
     FROM solving 
     GROUP BY solver, year 
    ) yt CROSS JOIN 
    (SELECT @y := 0, @rn := 0) vars 
ORDER BY year, TotalPoints DESC; 

然後用這個作爲一個子查詢,以獲得前三名:

SELECT yt.* 
FROM (SELECT yt.*, 
      (@rn := if(@y = year, @rn + 1, 
         if(@y := year, 1, 1) 
         ) 
      ) as seqnum 
     FROM (SELECT solver, year, SUM(points) as TotalPoints 
      FROM solving 
      GROUP BY solver, year 
      ) yt CROSS JOIN 
      (SELECT @y := 0, @rn := 0) vars 
     ORDER BY year, TotalPoints DESC 
    ) yt 
WHERE seqnum <= 3; 
+0

完美解釋。謝謝 – 2014-12-09 12:51:49

0

這可能會幫助你。

SELECT solver, 
    year, 
    SUM(points) AS TotalPoints 
FROM (
    SELECT solver, 
     year, 
     SUM(points) AS TotalPoints 
    FROM solving 
    ORDER BY year, 
     TotalPoints DESC 
    ) 
WHERE rownum <= 3 
ORDER BY year, 
    TotalPoints DESC;