列出具有最新日期的行

时间:2014-09-25 18:50:37

标签: sql-server tsql

我有一张列出合约日期的表格。合同可以有多个日期,所以我只想要最新的日期。

我尝试按合约排序日期排名,然后过滤以便我只获得第一排名,但我不断收到语法错误:

列名称'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中执行此操作?

谢谢!

1 个答案:

答案 0 :(得分:2)

排名函数无法在查询中进行操作,您需要使用外部查询来操作任何排名函数。

此外,您不需要使用MAX()函数来获取使用排名功能的最后日期,以下查询将返回表格中每个用户ID的最后合同结束日期。

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(Common Table Expression)来达到相同的效果。

;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