问题
I have a database table that looks like this:
| ID | TITLE | VERSION |
| 1 | file1 | 1 |
| 2 | file2 | 1 |
| 3 | file1 | 2 |
| 4 | file2 | 2 |
I need an SQL query that will return rows 3 and 4 because they are the latest versions of file1 and file 2.
If I run the query on a table that looks like this:
| ID | TITLE | VERSION |
| 1 | file1 | 1 |
| 2 | file2 | 1 |
| 3 | file1 | 2 |
| 4 | file2 | 2 |
| 5 | file3 | 1 |
It should return rows 3,4 and 5 because "file3" version1 is the latest version of file3.
I know I need to use "MAX" function in SQL, however I'm getting throw off with the "GROUP BY" keyword. I'm not very familiar with how to use it.
Would appreciate all / any advice!
We are using Oracle 11g.
回答1:
Indeed, use a subquery to obtain the MAX version, grouped by TITLE, and then join the result of it with your table to obtain the ID:
SELECT t.*
FROM tbl t INNER JOIN
(SELECT title, MAX(version) version
FROM tbl
GROUP BY title
) max_t ON (t.version = max_t.version AND t.title = max_t.title);
DEMO.
回答2:
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.
来源:https://stackoverflow.com/questions/12397330/how-do-you-select-only-the-maximum-version-of-a-list-of-documents-that-have-diff