[英]Comparing two max dates with a condition in Oracle SQL
我有如下数据
ID date state
1 24-Aug-18 Not defined
1 23-Aug-18 Incorrect
1 22-Aug-18 Incorrect
1 21-Aug-18 Incorrect
1 1-Aug-18 Correct
1 23-Jul-17 Incorrect
1 22-Jul-17 Incorrect
1 21-Jul-17 Incorrect
1 10-Jul-17 Correct
记录1进入“未定义”状态后,可以在3天内保持不正确的状态(除非尚未对记录进行任何更新。如果完成,则恢复为正确)。 必须避免未定义状态。 现在,我需要定义一个查询,以便该查询可以识别记录进入错误状态的最小最新记录日期,即在这种情况下为2018年8月21日。 这里的另一个问题是该表没有唯一键。
我一直在尝试下面的代码,但它抛出错误“ ORA-01427:单行子查询返回多个行”
select id, min(date) from table where state = 'Incorrect' group by id having
((Select trunc(MAX (date)) from table where state = 'Incorrect'
group by id) >= (select trunc(Max (date)) from table where state = 'Correct'
group by id))
嗯,我认为这可以满足您的需求:
select id, min(date) as min_latest_incorrect_date
from (select t.*,
max(case when state = 'Correct' then date end) over (partition by id) as max_date_correct
from t
) t
where (date > max_date_correct or max_date_correct is null) and
state = 'Incorrect'
group by id
对于每个ID,您正在寻找不正确的记录,后面没有任何正确的记录。 其中以第一。
select id, min(date)
from mytable i
where state = 'Incorrect'
and not exists
(
select *
from mytable c
where c.id = i.id
and c.state = 'Correct'
and c.date > i.date
)
group by id
order by id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.