2010-01-13 177 views
2

我已經得到了未知列下面的查詢被拋出以下錯誤with語句SQL,在where子句

未知列「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 

回答

3

嘗試wrpping您的查詢來獲得在where子句中

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

5

這是因爲別名不是在WHERE條款中確認。相反,使用完整的查詢是這樣的:

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

+1

使用名稱+1。發現。 GR8。 – Guru 2010-01-13 10:06:42

0

如何:

被等級說明選擇前10 * 從員工 爲了

另外,它沒有在那裏ROWNUM工作條款。 (爲什麼你們之間那麼棘手?)。

2

您的WHERE子句不能引用窗口或聚合函數,如ROW_NUMBER()。如果你想上的ROW_NUMBER()結果進行過濾,你需要的HAVING條款中這樣做:

... 
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