0

我正在尝试对按派生列排序的查询使用 SQL Server 2008 排名函数。这是一个例子

SELECT 
    table.FirstName, table.LastName, 
    CalculatedValue(table.number) As Points, 
    ROW_NUMBER() OVER (ORDER BY points) AS 'Row Number' 
FROM table 
ORDER BY points

我总是收到一个错误无效的列名“points”,因为根据我所读到的内容,OVER 函数不适用于别名。

有谁知道我可以检索按派生列排序的结果集的顺序行号的替代方法?

4

2 回答 2

3

使用派生表(子查询)怎么样?我认为类似下面的东西应该工作

SELECT 
    ROW_NUMBER() OVER (ORDER BY sub.Points) AS 'Row Number',
    sub.FirstName,
    sub.LastName,
    sub.Points
FROM
(

    SELECT 
        table.FirstName, 
        table.LastName, 
        CalculatedValue(table.number) As Points
    FROM 
        table    
) sub
ORDER BY
    sub.Points
于 2009-09-02T20:35:28.587 回答
2

使用 CTE 计算您的积分,然后在 CTE 上排名。

 WITH tableWithPoints AS (
   SELECT 
       table.FirstName, table.LastName, 
       CalculatedValue(table.number) As Points
   FROM table)

 SELECT FirstName, LastName, Points,
     ROW_NUMBER() OVER (ORDER BY Points) AS 'Row Number' 
 FROM 
     tableWithPoints ORDER BY Points
于 2009-09-02T20:41:56.297 回答