简体   繁体   中英

SQL Query to compare two most recently modified row of the same table

I am trying to write SQL query for following scenario

This is simple version of my table

ID      Value          modified Date

1      complete        12/18/2014
3      pending         12/12/2014
2      complete        12/14/2014
2      not started     12/10/2014
1      pending         12/11/2014
3      not started     12/12/2014
2      complete        12/16/2014
1      testing         12/13/2014
3      complete        12/17/2014

I am trying to get a list of IDs that has different "value" for two most recent modified date.

For eg In above table two most recent date for ID "1" is 12/18/2014 and 12/13/2014, corresponding values for that rows are "complete" and "testing", which are not equal, so that will be in my list.

However ID "2" will not be in the list because latest two modified date (12/14 and 12/16) for "2" has the same value "complete"

so result I want to get is

ID   Value  

1    Complete
3    Complete

I am using Oracle database

I am trying since last two days but never got a One query solution to present here.

Any help will be appreciated.

You can do this using row_number() and conditional aggregation:

select id, max(case when seqnum = 1 then value end) as value
from (select t.*, row_number() over (partition by id order by modifieddate desc) as seqnum
      from table t
     ) t
group by id
having max(case when seqnum = 1 then value end) <> max(case when seqnum = 2 then value end);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM