我正在尝试对按派生列排序的查询使用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函数不能使用别名。
有没有人知道我可以检索由派生列排序的结果集的连续行号的替代方法?
答案 0 :(得分: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
答案 1 :(得分: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