2012-05-11 88 views
0

我想分頁hiscore表。我有2個表:SQL Server分頁複雜查詢

gs_score_table

id (auto increment int) 
project_id (int) 
game_id (int) 
user_id (int) 
entry_date (datetime) 
score (int) 

用戶

id (auto increment int) 
user_name (varchar) 

我要的是scores DESC得到hiscores和順序列表的名單,但我總是錯誤第5行(此:ROW_NUMBER() OVER (ORDER BY total_score DESC) AS RowNumber),說:

無效的列名稱'total_score'。

任何人都可以幫忙。

SELECT TOP 50 
    * 
FROM 
    (SELECT 
     ROW_NUMBER() OVER (ORDER BY total_score DESC) AS RowNumber, 
     gs.user_id, 
     users.user_name, 
     SUM(gs.score) AS total_score, 
     (SELECT COUNT(gs2.id) FROM gs_score_table AS gs2 WHERE gs2.user_id = gs.user_id AND gs2.game_id = 1) AS games_played, 
     TotalRows=Count(*) OVER() 
    FROM 
     gs_score_table AS gs 
    INNER JOIN 
     users ON users.id = gs.user_id 
    WHERE 
     gs.project_id = 2 
     AND gs.game_id = 1 
     AND CAST(gs.entry_date AS date) BETWEEN '2012-04-23' AND '2012-04-23' 
    GROUP BY 
     gs.user_id, users.user_name) _tmpInlineView WHERE RowNumber >= 1 

回答

1

不能在ROW_NUMBER ORDER BY子句中使用別名「total_score」。相反,您需要:

ROW_NUMBER() OVER (ORDER BY SUM(gs.score) DESC) AS RowNumber 
+0

非常感謝。而已。 – Tjodalv