1

I have a table with data like this:

Id     | Version | isLive
-------+---------+-------
comp1  |   2     | true     
comp1  |   3     | true     
comp1  |   4     | false    
comp1  |   1     | true      
comp2  |   4     | true      
comp2  |   1     | false

I want to fetch the row that has the highest version number per ID. So there should only be one row per ID.

select id 
from mytable 
group by id

This returns the data randomly.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
codeNinja
  • 1,442
  • 3
  • 25
  • 61

3 Answers3

0

From here

SELECT * FROM (SELECT * FROM MyTbl ORDER BY version ) WHERE rownum = 1;
Johann
  • 349
  • 2
  • 9
0

Is this what you want ?

         select id,max(distinct version) from 
         mytable 
        group by id order by id
Himanshu
  • 3,830
  • 2
  • 10
  • 29
0

How about this:

SQL> with test (id, version, islive) as
  2    (select 'comp1', 2, 'true'  from dual union all
  3     select 'comp1', 3, 'true'  from dual union all
  4     select 'comp1', 4, 'false' from dual union all
  5     select 'comp1', 1, 'true'  from dual union all
  6     select 'comp2', 4, 'true'  from dual union all
  7     select 'comp2', 1, 'false' from dual
  8    )
  9  select id, version, islive
 10  from (select id, version, islive,
 11          row_number() over (partition by id order by version desc) rn
 12        from test
 13       )
 14  where rn = 1;

ID       VERSION ISLIV
----- ---------- -----
comp1          4 false
comp2          4 true

SQL>
Littlefoot
  • 131,892
  • 15
  • 35
  • 57