2010-07-23 56 views
1

我有一個網站可以收集遊戲的高分 - 側欄顯示最新的10個分數(不一定是最高的,只是最新的10個)。但是,由於用戶可以快速玩多個遊戲,他們可以控制最近的10個列表。我如何編寫SQL squery來顯示最後10個分數,但將其限制爲每個用戶一個?SQL - 每個用戶記錄一個結果

+1

哪個數據庫? – CJM 2010-07-23 15:12:00

+0

如果用戶玩過5場比賽,所有5場比賽的比分是否加在一起,還是隻取得最高比分? – 2010-07-23 15:13:20

回答

7
SELECT username, max(score) 
FROM Sometable 
GROUP BY username 
ORDER BY Max(score) DESC 

並從中選擇最高的X取決於您的數據庫平臺。選擇MS-SQL 2005+

編輯

對不起頂(10),我看到你想要的東西是按日期順序。

這裏有一個工作查詢與MS-SQL 2005

; 
WITH CTE AS 
(
SELECT ROW_NUMBER() OVER (PARTITION BY username ORDER BY dateadded DESC) AS 'RowNo', 
username, score, dateadded FROM SomeTable 
) 
SELECT username, score, dateadded FROM CTE 
WHERE RowNo = 1 
+1

海報需要最新的10個分數,即來自10個用戶的最新分數,而不是最高分數。按分數排序或顯示MAX(分數)是沒有意義的。 – 2010-07-23 15:17:27

+0

優秀的答案,這是我需要的 – 2010-07-23 16:02:48

0

集團用戶...,要麼選擇MAX(分數),馬克斯([投稿日期])或什麼的。

0

在SQL Server中,您可以使用適當的PARTITION和GROUP BY的RANK()OVER(),但您使用的平臺是什麼?

0

在提供另一個角度來看,你可能只是一個領域的「最高分」添加到您的用戶表,然後用一個簡單的查詢與訂單的獲得前10名。

你的更新將利益需要檢查新分數是否高於當前最高分數。

它具有查詢表格的優點,該表格最有可能具有較少的行,然後是您的分數表。

無論如何,只是另一種選擇考慮。

0

這裏是工作的例子,我建立在SQL Server 2008上

WITH MyTable AS 
(
    SELECT 1 as UserId, 10 as Score UNION ALL 
    SELECT 1 as UserId, 11 as Score UNION ALL 
    SELECT 1 as UserId, 12 as Score UNION ALL 
    SELECT 2 as UserId, 13 as Score UNION ALL 
    SELECT 2 as UserId, 14 as Score UNION ALL 
    SELECT 3 as UserId, 15 as Score UNION ALL 
    SELECT 3 as UserId, 16 as Score UNION ALL 
    SELECT 3 as UserId, 17 as Score UNION ALL 
    SELECT 4 as UserId, 18 as Score UNION ALL 
    SELECT 4 as UserId, 19 as Score UNION ALL 
    SELECT 5 as UserId, 20 as Score UNION ALL 
    SELECT 6 as UserId, 21 as Score UNION ALL 
    SELECT 7 as UserId, 22 as Score UNION ALL 
    SELECT 7 as UserId, 23 as Score UNION ALL 
    SELECT 7 as UserId, 24 as Score UNION ALL 
    SELECT 8 as UserId, 25 as Score UNION ALL 
    SELECT 8 as UserId, 26 as Score UNION ALL 
    SELECT 9 as UserId, 26 as Score UNION ALL 
    SELECT 10 as UserId, 20 as Score 
), 
MyTableNew AS 
(
    SELECT Row_Number() OVER (Order By UserId) Sequence, * 
    FROM MyTable 
), 
RankedUsers AS 
(
    SELECT *, Row_Number() OVER (Partition By UserId ORDER BY Sequence DESC) Ranks 
    FROM MyTableNew 
) 
SELECT * 
FROM MyTableNew 
WHERE Sequence IN 
(
    SELECT TOP 5 Sequence 
    FROM RankedUsers 
    WHERE Ranks = 1 
    ORDER BY Sequence DESC 
) 
0
SELECT s2.* 

FROM 
(SELECT user_id, MAX(action_time) AS max_time 
FROM scores s1 GROUP_BY user_id 
ORDER BY MAX(action_time) DESC LIMIT 10)s1 
INNER JOIN scores s2 ON (s2.user_id = s1.user_id AND s2.action_time = s1.max_time)   

這是Mysql的語法,用於SQL服務器,您需要使用SELECT TOP 10 ...而不是LIMIT 10

相關問題