我有如下数据
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天后,它去‘未定义’(除非任何更新尚未对记录。如果完成了,它就会回到正确的位置)。必须避免未定义的状态。现在,我需要定义一个查询,以便该查询能够识别记录进入不正确状态的最小最新记录日期,即在本例中是21-8月-2018年。另外,这里的问题是表没有唯一的键。
我一直在尝试下面的代码,但是它正在抛出错误'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))发布于 2018-08-26 11:21:03
嗯,我想这能做你想做的事:
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发布于 2018-08-26 11:25:20
每个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;https://stackoverflow.com/questions/52025689
复制相似问题