How do you select only the maximum version of a list of documents that have different versions in SQL?

后端 未结 2 483
猫巷女王i
猫巷女王i 2021-01-26 06:56

I have a database table that looks like this:

| ID | TITLE | VERSION | 
| 1  | file1 |    1    |
| 2  | file2 |    1    |
| 3  | file1 |    2    |
| 4  | file2          


        
2条回答
  •  生来不讨喜
    2021-01-26 07:44

    Actually the best way to do this is using the ranking functions:

    select id, title, version
    from (select t.*
                 row_number() over (partition by id order by version desc) as seqnum
          from t
         ) t
    where seqnum = 1
    

    The function row_number() is called an analytic function in Oracle. It assigns number 1, 2, 3 . . . to each row, based on the partitioning clause. The numbers start over at each id, and the largest version starts at 1.

提交回复
热议问题