Skip to content
Advertisement

How to get entries which are grouped and satisfy restriction within the group?

In the table REPORT there are following 3 columns:

  • RID – report id, which is not unique
  • TYPE – can be either new or cancel, report is identified by RID, so one report can have multiple cancellations and multiple new entries
  • TIMESTAMP – is just a timestamp of when entry arrived

Example below:

I’d like to get all reports which at some point were created and then canceled, so that the latest state is canceled. It is possible to have cancellations of non-existed reports, or entries with first cancellations and then new entries, all of those should be excluded.

My attempt so far was to use nested query to get all cancellations, which have corresponding new entry, but do not know how to consider their timestamps into consideration, to exclude entries which have sequence cancel->new

My expectation from the example is to get RID 1, I’m interested in only RIDs.

Using: MySQL 5.7.27 InnoDB

Advertisement

Answer

With EXISTS:

See the demo.
Or:

See the demo.
Results:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement