简体   繁体   中英

Comparing two max dates with a condition in Oracle SQL

I have the data as below

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

The record 1 can stay at the incorrect state for 3 days post that it goes to 'not defined' (unless any update has not been made to the record. If done then it gets back to Correct). The not defined state has to be avoided. Now I need to define a query such that the query can identify the minimum latest record date at which the record went to the incorrect state ie in this case 21-Aug-2018. Also problem here is the table doesn't have unique keys.

I have been trying the below code but it is throwing me the error 'ORA-01427: single-row subquery returns more than one row'

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

Hmmm, I think this does what you want:

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

Per ID, you are looking for incorrect records that are not followed by any correct record. Of these take the first.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM