2

I ve got the following query which is throwing the following error

Unkown Column 'RowNum'

WITH Employees AS
(
SELECT
   (keyTblSp.RANK * 3) AS [Rank],
    sp.*,
    addr.Street,
    addr.PostOfficeBox,
    addr.StreetNumber
FROM Employee sp    
    INNER JOIN 
        FREETEXTTABLE(Employee, *, 'something', 1000) AS keyTblSp
        ON sp.EmployeeId = keyTblSp.[KEY]    
    LEFT OUTER JOIN [Address] addr ON addr.EmployeeId = sp.EmployeeId 
UNION ALL
SELECT
    (keyTblAddr.RANK * 2) AS [Rank],
    sp.*,
    addr.Street,
    addr.PostOfficeBox,
    addr.StreetNumber
FROM Employee sp    
    LEFT OUTER JOIN [Address] addr ON addr.EmployeeId = sp.EmployeeId 
    INNER JOIN 
        FREETEXTTABLE([Address], *, 'something', 1000) AS keyTblAddr
        ON addr.AddressId = keyTblAddr.[KEY]
)

SELECT ROW_NUMBER() OVER (ORDER BY [Rank] DESC) AS RowNum, *
FROM Employees
WHERE RowNum BETWEEN (1 - 1) * 10 + 1 AND 1 * 10
ORDER BY Rank DESC
Chris
  • 7,229
  • 7
  • 41
  • 57

4 Answers4

5

This is because aliases are not recognized in WHERE clauses. Instead, use the full query like this:

WHERE ROW_NUMBER() OVER (ORDER BY [Rank] DESC) BETWEEN (1 - 1) * 10 + 1 AND 1 * 10

KJ Saxena
  • 21,452
  • 24
  • 81
  • 109
3

Try wrpping up your query to get the name usable in the where clause

SELECT
    *
FROM
    (SELECT
        ROW_NUMBER() OVER (ORDER BY [Rank] DESC) AS RowNum
    ,   *
    FROM
        Employees) AS Results
WHERE
    RowNum BETWEEN (1 - 1) * 10 + 1 AND 1 * 10
ORDER BY
    Rank
jdhao
  • 24,001
  • 18
  • 134
  • 273
Robert
  • 3,328
  • 2
  • 24
  • 25
2

Your WHERE clause cannot refer to a window or aggregate function like ROW_NUMBER(). If you want to filter on the result of ROW_NUMBER(), you need to do so in the HAVING clause:

...
SELECT ROW_NUMBER() OVER (ORDER BY [Rank] DESC) AS RowNum, *
FROM Employees
HAVING RowNum BETWEEN (1 - 1) * 10 + 1 AND 1 * 10    
ORDER BY Rank DESC    
Roland Bouman
  • 31,125
  • 6
  • 66
  • 67
0

How about:

select top 10 * from Employees order by Rank Desc

Alternatively, does it work without the where rownum clause. (why is your between so tricky?).