SQL获取当前版本

时间:2016-08-31 19:51:22

标签: sql oracle group-by max

我有一个表记录了另一个表的修订:

修订版(r)

id     protocol     year     revision_created
----------------------------------------------------
100    PR00001      2015     7/29/2015 10:00:00 AM
101    PR00001      2015     8/29/2015 09:00:00 AM
102    PR00001      2016     2/12/2016 09:30:00 AM
250    PR00002      2016     3/10/2016 10:00:00 AM
251    PR00002      2016     3/10/2016 04:00:00 PM
252    PR00002      2016     8/31/2016 02:48:00 PM

我想获得每年每个协议的所有最新版本的id,所以在这种情况下我想得到:

id     year    protocol
--------------------------
101    2015    PR00001
102    2016    PR00001
252    2016    PR00002

我有这个查询但它有效,但我觉得我不应该在MAX字段上使用id,而是在revision_created字段上使用它 - 但是如果我这样做的话然后我不会得到id。想法或建议?

SELECT MAX(r.id) AS id, r.year, r.protocol
FROM revision r
GROUP BY r.year, r.protocol

2 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER

SELECT id, year, protocol
FROM (  SELECT *,
               ROW_NUMBER() OVER(PARTITION BY protocol, year ORDER BY revision_created DESC) RN
        FROM revision) AS r
WHERE RN = 1

如果您无法使用ROW_NUMBER,则可以使用同一个表加入:

SELECT r1.id, r1.year, r1.protocol
FROM revision r1
INNER JOIN (SELECT  protocol,
                    year,
                    MAX(revision_created) Max_Revision
            FROM revision
            GROUP BY protocol,
                     year) r2
    ON r1.protocol = r2.protocol
    AND r1.year = r2.year
    AND r1.revision_created = r2.Max_Revision

答案 1 :(得分:1)

在Oracle中,您可以使用聚合和keep

SELECT r.protocol, r.year,
       MAX(id) KEEP (DENSE_RANK FIRST ORDER BY r.revision_created DESC) as id
FROM revision r
GROUP BY r.year, r.protocol;