【问题标题】:Comparing two max dates with a condition in Oracle SQL将两个最大日期与 Oracle SQL 中的条件进行比较
【发布时间】:2019-02-01 04:30:22
【问题描述】:

我有如下数据

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))

【问题讨论】:

  • 请编辑问题并显示您想要的结果。
  • 所以我试图获取记录进入不正确状态的最新最低日期,即在这种情况下为 2018 年 8 月 21 日。

标签: sql oracle max min


【解决方案1】:

嗯,我认为这是你想要的:

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

【讨论】:

  • 那应该是where (date > max_date_correct or max_date_correct is null),但我认为,对于 ID 从未正确的情况。
  • @ThorstenKettner 。 . .我同意。谢谢。
【解决方案2】:

对于每个 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多