2014-09-25 93 views
1

我有一個列出合同日期的表。合同可以有多個日期,所以我只想要最近的一個。列出具有最近日期的行

我試圖通過contractEnded日期排序,然後過濾,這樣我只得到了第一個排名,但我不斷收到一個語法錯誤:

無效的列名稱contractRank「。

SELECT MAX(contractEnded) AS contractEnded, contractID, contractStarted, contractEnded, userID, examID, 
ROW_NUMBER() OVER (
        partition by userID 
        ORDER BY MAX(contractEnded) desc) 
        AS contractRank 
FROM examcontract es 
WHERE examID = 92855231134 
and es.contractRank = 1 
GROUP BY userID, examID, contractID, contractStarted, contractEnded 

有沒有辦法在MSSQL 2012年做到這一點?

謝謝!

+2

您不能在'WHERE','ON','GROUP BY'等的select子句中使用別名。使用CTE。 'WITH x AS(SELECT MAX ...)SELECT * FROM x WHERE contractRank = 1;' – 2014-09-25 18:52:56

回答

2

排名函數無法在查詢中使用,您將需要使用外部查詢來操作任何排名函數。

另外,您不需要使用MAX()函數來獲取使用Ranking函數的最後日期,下面的查詢將返回表中每個用戶ID的Last Contract結束日期。

SELECT contractEnded, contractID, contractStarted, contractEnded, userID, examID 
FROM (
    SELECT contractEnded, contractID, contractStarted, contractEnded, userID, examID, 
     ROW_NUMBER() OVER (partition by userID ORDER BY contractEnded desc) AS contractRank 
    FROM examcontract 
    WHERE examID = 92855231134 
    )A 
WHERE A.contractRank = 1 

正如Aaron在您的評論部分中提到的,您也可以使用CTE(公用表表達式)來實現相同的結果。

;WITH CTE AS 
(
    SELECT contractEnded, contractID, contractStarted, contractEnded, userID, examID, 
    ROW_NUMBER() OVER (partition by userID ORDER BY contractEnded desc) AS contractRank 
    FROM examcontract es 
    WHERE examID = 92855231134 
) 
SELECT contractEnded, contractID, contractStarted, contractEnded, userID, examID 
FROM CTE 
WHERE contractRank = 1