[英]SQL Query to compare two most recently modified row of the same table
I am trying to write SQL query for following scenario 我正在尝试为以下情况编写SQL查询
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. 我正在尝试获取两个最近修改日期具有不同“值”的ID列表。
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. 例如,在上表中,ID为“ 1”的两个最新日期为2014年12月18日和2014年12月13日,该行的对应值分别为“完成”和“测试”,它们不相等,因此将为在我的清单中。
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" 但是,ID“ 2”将不在列表中,因为“ 2”的最近两个修改日期(12/14和12/16)具有相同的值“ complete”
so result I want to get is 所以我想要得到的结果是
ID Value 1 Complete 3 Complete
I am using Oracle database 我正在使用Oracle数据库
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: 您可以使用row_number()
和条件聚合来做到这一点:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.