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

2
  • 1
    Tag your question with the database you are using. Do you have a unique id on each row? Commented Jun 28, 2019 at 12:10
  • What in cases of "ties" where the status MAX() value is the same in the ID, VERSION group? Do you need both records or just a single.. Commented Jun 28, 2019 at 12:38

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

1 Comment

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..
1
select id,max(version),max(status) from 
table1
group by id

1 Comment

Topicstarter you would most like have to add a ORDER BY ID as MySQL 8 does not sort GROUP BY annymore..
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

Comments

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;

Comments

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

1 Comment

the SQL tag is about writing ANSI/ISO SQL standard code not about SQL Server (MSSQL)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.