2014-03-29 86 views
0

我想在SQL查詢中進行分頁和排序。Row_Number()Over Order By計算機列

這裏是我的查詢

;WITH myCTE AS 
(SELECT (FirstName+''+LastName) as [User Name], 
     ROW_NUMBER() OVER (ORDER BY FirstName) as RowID 
     From [MyTable]) 

SELECT TOP 10 * FROM myCTE 
    WHERE RowID > 10*(2-1) 

它工作正常,但現在我想通過計算列[用戶名]

所以我改變了這樣的查詢

來記錄進行排序
;WITH myCTE AS 
(SELECT (FirstName+''+LastName) as [User Name], 
     ROW_NUMBER() OVER (ORDER BY [User Name] ASC) as RowID 
     From [MyTable]) 

SELECT TOP 10 * FROM myCTE 
    WHERE RowID > 10*(2-1) 

但它給出了這個錯誤:

Msg 207, Level 16, State 1, Line 2 
Invalid column name 'User Name'. 

任何人都可以幫助我如何使用ROW_NUMBER()OVER計算列?或者我如何在SQL查詢中實現排序和分頁記錄?

回答

7

只是指實際的表達在order by,而不是別名:

;WITH myCTE AS 
(SELECT (FirstName+''+LastName) as [User Name], 
     ROW_NUMBER() OVER (ORDER BY FirstName+''+LastName ASC) as RowID 
     From [MyTable]) 

SELECT TOP 10 * FROM myCTE 
    WHERE RowID > 10*(2-1) 
0
DECLARE @pageNumber int, 
     @page_Size int, 
     @page_start int 

SET @pageNumber = 1 
SET @page_Size = 10 
SET @page_start = ((@page_Size-1) * @pageNumber) + 1 
Select TOP(@page_Size)<valiables_names>,ROW_NUMBER() [Row_ID] from <table_Name> having Row_ID >= @page_start 
0

兩件事情。首先,您不能引用同一條SELECT子句中的其他列,因爲所有列都是「並行」有效計算的,因此新創建的值不可用。一種方法是重複表達伊恩的answer顯示,另一種方式是引入另一個CTE:

;WITH CombinedNames AS 
(
    SELECT (FirstName+''+LastName) as [User Name] 
    FROM MyTable 
), Numbered as 
(
    SELECT [User Name], 
     ROW_NUMBER() OVER (ORDER BY [User Name]) as RowID 
     From CombinedNames 
) 
SELECT TOP 10 * FROM Numbered 
    WHERE RowID > 10*(2-1) 

但是,這是很重要的,這實際上仍然打破。爲什麼?因爲你沒有應用任何ORDER BY到最後的SELECT使用TOP來選擇10行 - 所以你沒有得到「應該出現在第2頁的10行」,你會得到「任何隨機的10行' t出現在第1頁「。因此,我們需要再作更改:

;WITH CombinedNames AS 
(
    SELECT (FirstName+''+LastName) as [User Name] 
    FROM MyTable 
), Numbered as 
(
    SELECT [User Name], 
     ROW_NUMBER() OVER (ORDER BY [User Name]) as RowID 
     From CombinedNames 
) 
SELECT TOP 10 * FROM Numbered 
    WHERE RowID > 10*(2-1) 
ORDER BY RowID 

或者如果你喜歡:

;WITH CombinedNames AS 
(
    SELECT (FirstName+''+LastName) as [User Name] 
    FROM MyTable 
), Numbered as 
(
    SELECT [User Name], 
     ROW_NUMBER() OVER (ORDER BY [User Name]) as RowID 
     From CombinedNames 
) 
SELECT TOP 10 * FROM Numbered 
    WHERE RowID > 10*(2-1) AND RowID <= 10*2 

但請注意這第二個變體並不能保證在頁面中返回結果的順序。

+0

謝謝你....這就是我想要的 – kombsh

相關問題