1

I have a table as below

--------Table 1----------
ID     VERSION     STATUS
001       1          1
001       1          2
002       1          3
002       2          4
002       2          3        

So here I need to filter the ID's based on the max value of version and status. The expected result is below

--------Table 1----------
ID     VERSION     STATUS
001       1          2
002       2          4

I tried using the code

select * 
from "table1" 
where "VERSION" = (select max("VERSION") from  "table1") 
  and "STATUS" = (select max("STATUS") from "table1")

But it is not working. Please help

Arun Elangovan
  • 237
  • 1
  • 3
  • 16

5 Answers5

1

Unless I'm missing something obvious, a simple group by with max should do it:

SELECT ID, MAX(VERSION) As Version, MAX(STATUS) As Status
FROM table1
GROUP BY ID
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • indeed i also was wondering about the window function answers, Topicstarter you would most like have to add a `ORDER BY ID` as MySQL 8 does not sort GROUP BY annymore.. – Raymond Nijland Jun 28 '19 at 12:45
1
select id,max(version),max(status) from 
table1
group by id
Kedar Limaye
  • 1,041
  • 8
  • 15
0

most dbms support row_number(), you can try like below

   select * from 
    (select *,row_number() over(partition by id order by status desc) rn
    from table_name
    ) a where a.rn=1
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63
0

You can use row_number():

select t.*
from (select t.*,
             row_number() over (partition by id order by version desc, status desc) as seqnum
      from t
     ) t
where seqnum = 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Try this:

select id,version,status from (
select *,ROW_NUMBER() over (partition by id order by status desc) rn from YOURTABLE
) t
where rn=1
Red Devil
  • 2,343
  • 2
  • 21
  • 41