Using a SQL Ranking Function with a derived column
-
21-09-2019 - |
Question
I am trying to use a SQL Server 2008 Ranking Function on a query sorted by a derived column. Here's an example
SELECT
table.FirstName, table.LastName,
CalculatedValue(table.number) As Points,
ROW_NUMBER() OVER (ORDER BY points) AS 'Row Number'
FROM table
ORDER BY points
I always get an error invalid column name "points" because the OVER function does not work with aliases, based on what I've read.
Does anyone know an alternative where I can retrieve the sequential row number of a result set sorted by a derived column?
Solution
How about using a derived table (sub query)? I think something like the following should work
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
OTHER TIPS
Use a CTE to calculate your Points, then rank over the 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow