2008-09-01 90 views
6

我想找到解決現實生活問題的不同方式:想象要舉辦比賽或遊戲,期間用戶收集點。您必須建立查詢以顯示具有最佳「n」分數的用戶列表。SQL查詢從列表中獲得最高的「n」分數

我正在做一個例子來澄清。比方說,這是用戶表,用點獲得:

UserId - Points 
1  - 100 
2  - 75 
3  - 50 
4  - 50 
5  - 50 
6  - 25 

如果我想的前3名的分數,其結果將是:

UserId - Points 
1  - 100 
2  - 75 
3  - 50 
4  - 50 
5  - 50 

這可以在視圖或實現存儲過程,只要你想。我的目標數據庫是Sql Server。其實我解決了這個問題,但我認爲有不同的方法來獲得結果...比我的更快或更有效率。

回答

9

未經檢驗的,但應該工作:

select * from users where points in 
(select distinct top 3 points from users order by points desc) 
1

@bosnic,我不認爲的要求,將工作,我沒那麼熟悉MS SQL,但我希望它僅返回3行,並且忽略3個用戶並列第3名的事實。

像這樣的東西應該工作:

select userid, points 
    from scores 
    where points in (select top 3 points 
         from scores 
         order by points desc) 
    order by points desc 
0

@Espo感謝現實檢測 - 增加了子選擇來糾正這一點。

我認爲最簡單的迴應是:

select userid, points from users 
where points in (select distinct top N points from users order by points desc) 

如果你想要把在一個存儲過程,其採用N作爲參數,那麼你要麼必須做閱讀SQL到一個變量然後執行它,或做行數招:

declare @SQL nvarchar(2000) 
set @SQL = "select userID, points from users " 
set @SQL = @SQL + " where points in (select distinct top " + @N 
set @SQL = @SQL + " points from users order by points desc)" 

execute @SQL 

SELECT UserID, Points 
FROM  (SELECT ROW_NUMBER() OVER (ORDER BY points DESC) 
     AS Row, UserID, Points FROM Users) 
     AS usersWithPoints 
WHERE Row between 0 and @N 

這兩個示例都假定SQL Server並沒有經過測試。

0

@羅布#37760:

select top N points from users order by points desc 

這個查詢只能選擇3行,如果N爲3,看問題。 「前3名」應該返回5行。

1

關於如何:

select top 3 with ties points 
from scores 
order by points desc 

不知道是否 「有關係」 的作品上的任何其他的SQL Server。

在SQL Server 2005和了,你可以通過「頂」號作爲一個int參數:

select top (@n) with ties points 
from scores 
order by points desc 
4

這裏有一個工程 - 我不知道這是否是更高效,它的SQL服務器2005+

with scores as (
    select 1 userid, 100 points 
    union select 2, 75 
    union select 3, 50 
    union select 4, 50 
    union select 5, 50 
    union select 6, 25 
), 
results as (
    select userid, points, RANK() over (order by points desc) as ranking 
    from scores 
) 
select userid, points, ranking 
from results 
where ranking <= 3 

顯然,第一個「用」是設置的值,這樣你就可以測試第二位,並最終選擇的工作 - 你可以在「結果如......」開始,如果你是查詢現有的表格。

+0

我有一個類似的問題,並試圖使用MAX,然後我讀你的回答並記住了DENSE_RANK。爲我節省了很多時間。 – DataGirl 2012-06-21 20:49:47

0

@馬特漢密爾頓

你的答案可與上面的例子,但也不會工作,如果數據集爲100,75,75,50,50(它會返回只有3行)。 TOP WITH WITH TIES只包括返回的最後一行的關係...

0

坩堝得到它(假設SQL 2005是一個選項)。

0

實際上,使用INNER JOIN修改WHERE IN會更快。

SELECT 
    userid, points 
FROM users u 
INNER JOIN 
(
    SELECT DISTINCT TOP N 
     points 
    FROM users 
    ORDER BY points DESC 
) AS p ON p.points = u.points 
0

試試這個

select top N points from users order by points desc 
0

嘿,我發現所有的其他的答案有點長,效率低下 我的答案是:

select * from users order by points desc limit 0,5

這將使前5分

相關問題