views:

387

answers:

2

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?

+2  A: 

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
Russ Cam
Result set won't have all the columns OP is asking for. And the ORDER BY on the derived table will have no affect. Derived tables return relations, an unordered set (bag) of rows.
Shannon Severance
I realised I missed the other columns out - included now :)
Russ Cam
This worked very well. Thanks for helping.
wrburgess
+2  A: 

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
richardtallent
I know this will work, as well, but I used the other answer. Thanks for helping!
wrburgess