首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将两个最大日期与Oracle SQL中的条件进行比较

将两个最大日期与Oracle SQL中的条件进行比较
EN

Stack Overflow用户
提问于 2018-08-26 11:15:09
回答 2查看 1.4K关注 0票数 1

我有如下数据

代码语言:javascript
复制
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:单行子查询返回多行‘。

代码语言:javascript
复制
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))
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-26 11:21:03

嗯,我想这能做你想做的事:

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2018-08-26 11:25:20

每个ID,您正在寻找不正确的记录,但后面没有任何正确的记录。其中的第一个。

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52025689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档