Search code examples
sqloraclegreatest-n-per-group

SQL: getting the max value of one column and the corresponding other columns


ID|  tag  |  version
-----+-----+-----
1|  A  |  10
2|  A  |  20
3|  B  |  99
3|  C  |  30
3|  F  |  40

desired output:

1 A 10
2 A 20
3 B 99

How can I get the max version of every ID and the corresponding tag for that version? Speed is important (I have around 28m rows) so a nested Select won't do it. Also a simple Group by ID with a max(version) doesn't work because I also need the corresponding Tag where the version is max.


Solution

  • Use ROW_NUMBER() :

    SELECT s.id,s.tag,s.version FROM (
        SELECT t.*,
               ROW_NUMBER() OVER(PARTITION BY t.id ORDER BY t.version DESC) as rnk
       FROM YourTable t) s
    WHERE s.rnk = 1