SQL从结果集T-SQL中获取最新记录

时间:2015-09-24 21:28:15

标签: sql sql-server

我想检索最新版本的最新合约。 内部查询有效,但不幸的是,我需要找到一种方法使其在另一个查询中运行时...

这有效:

SELECT * FROM contract t1
WHERE revisionnum = (select max(revisionnum) 
                     from contract t2 
                     where t1.contractnum = t2.contractnum)`

问题是它在select * from contract where语句中,所以它看起来像这样:

SELECT * 
FROM contract 
WHERE -- this line cannot be changed!
exists -- not sure about this
(   SELECT * FROM contract t1
    WHERE revisionnum = (select max(revisionnum) 
                         from contract t2 
                         where t1.contractnum = t2.contractnum) 
)

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我之前看到有人使用过这样的东西..

SELECT * 
FROM contract 
WHERE 1 = (Select Count(*) 
           From contract c1 
           Where c1.contractnum = contract.contractnum And c1.revisionnum >= contract.revisionnum)

EXISTS 选项

SELECT  *
FROM    [contract]
WHERE   EXISTS ( SELECT c1.contractnum,
                        MAX(c1.revisionnum)
                 FROM   [contract] c1
                 WHERE  c1.contractnum = [contract].contractnum
                 GROUP BY c1.contractnum
                 HAVING MAX(c1.revisionnum) = [contract].revisionnum )

您的原始查询也非常接近..您只是错过了一个小过滤器并使用字段名称别名来指定您指向的表。

SELECT  *
FROM    contract
WHERE   EXISTS -- not sure about this
            ( SELECT    *
                FROM    contract t1
                WHERE   contract.contractnum = t1.contractnum -- filter missing
                        AND contract.revisionnum = (SELECT  MAX  (t2.revisionnum) -- missing table specifier
                                                    FROM    contract t2 
                                                    WHERE t1.contractnum = t2.contractnum) 
            )

答案 1 :(得分:0)

SELECT IDENT_CURRENT([TABLE_NAME])AS returnID