Write SQL To Merge Events With Overlapping Dates
Write SQL To Merge Events With Overlapping Dates
Interview Question
SQL
1 2023-01-13 2023-01-17
2 2022-12-09 2022-12-23
3 2022-12-01 2023-01-30
3.Second SELECT query after UNION we using to get
the records WHERE start_date >previous_end_date.
This will help us to get those records which are not
within any criteria range.
1 2023-01-18 2023-01-25
FINAL OUTPUT
1 2023-01-13 2023-01-17
1 2023-01-18 2023-01-25
2 2022-12-09 2022-12-23
3 2022-12-01 2023-01-30
QUERY FROM ANKIT SIR
QUERY EXPLANATION
1.With iterator_cte we are simply providing a
numbering to the records so that we can iterate
using the recursive cte.
1 2023-01-13 2023-01-14 1
1 2023-01-14 2023-01-17 2
1 2023-01-15 2023-01-17 3
1 2023-01-18 2023-01-25 4
2 2022-12-09 2022-12-23 5
2 2022-12-13 2022-12-17 6
3 2022-12-01 2023-01-30 7
2.Now we are using rcte for recursively running the
query.
The first query before UNION is an anchor query that
will act as our first start from where we will begin
iterating.
Here we are flaging the record as 1 so that we can
group them together if they fulfill the criteria.
1 2023-01-13 2023-01-14 1 1
1 2023-01-14 2023-01-17 2 1
1 2023-01-15 2023-01-17 3 1
1 2023-01-18 2023-01-25 4 2
2 2022-12-09 2022-12-23 5 3
2 2022-12-13 2022-12-17 6 3
3 2022-12-01 2023-01-30 7 4
4.Now we simply querying for the records records
that is hall_id, MIN(start_date) and MAX(end_date)
for each id by merging the overlapping dates.
We are eliminating the overlapping dates by
grouping them on the basis of hall_id and flag that
we created to group the records.
1 2023-01-13 2023-01-17
1 2023-01-18 2023-01-25
2 2022-12-09 2022-12-23
3 2022-12-01 2023-01-30
BY MANISH KUMAR CHAUDHARY
THANK YOU
"Success is not about being the best. It's
about always getting better."
Behdad Sami