Row_Number()按计算机列排序

时间:2014-03-29 11:38:33

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我想在SQL查询中进行分页和排序。

这是我的查询

;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查询中实现排序和分页记录?

3 个答案:

答案 0 :(得分: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) 

答案 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

答案 2 :(得分:0)

两件事。首先,您不能引用同一SELECT子句中的其他列,因为所有列都是“并行”有效计算的,因此新创建的值不可用。一种方法是重复表达式,如Ian的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选择10行的最终TOP,所以您没有获得“应该出现在第2页的10行”,你得到“第1页上没有出现的随机10行”。所以我们需要做出另一个改变:

;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

但请注意,第二个版本不保证页面内返回结果的顺序。