|
| 1 | +-- cte1- unioned both tables and arranged in ascending order of dates |
| 2 | +-- cte2- calculated rn and rnk and diff between them |
| 3 | +-- final query- picked min date as start date, max date as end date, grouped by status and diff |
| 4 | +-- rank()- gave them ranking based on their status ascending order date |
| 5 | +-- row_number()- ordered by date asc |
| 6 | +-- diff between them will be consistent if they are contiguous, hence group by diff |
| 7 | +-- when the status changes, again diff between them will be contiguous hence group by status to get different records for same status |
| 8 | + |
| 9 | +with cte1 as |
| 10 | + ((select fail_date as event_date, 'failed' as status |
| 11 | + from Failed) |
| 12 | + union all |
| 13 | + (select success_date as event_date, 'succeeded' as status |
| 14 | + from Succeeded)), |
| 15 | + cte2 as |
| 16 | + (select *, |
| 17 | + row_number() over(order by event_date) as rn, |
| 18 | + dense_rank() over (partition by status order by event_date) as rnk, |
| 19 | + row_number() over(order by event_date) - dense_rank() over (partition by status order by event_date) as diff |
| 20 | + from cte1 |
| 21 | + where event_date between '2019-01-01' and '2019-12-31' |
| 22 | + order by 1) |
| 23 | + |
| 24 | +select status as period_state, min(event_date) as start_date, max(event_date) as end_date |
| 25 | +from cte2 |
| 26 | +group by status, diff |
| 27 | +order by 2 |
| 28 | + |
| 29 | +-- facebook- 1 |
| 30 | + |
| 31 | +------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 32 | + |
| 33 | +-- o/p of cte2 |
| 34 | + |
| 35 | +| event_date | status | rn | rnk | diff | |
| 36 | +| ---------- | --------- | -- | --- | ---- | |
| 37 | +| 2019-01-01 | succeeded | 1 | 1 | 0 | |
| 38 | +| 2019-01-02 | succeeded | 2 | 2 | 0 | |
| 39 | +| 2019-01-03 | succeeded | 3 | 3 | 0 | |
| 40 | +| 2019-01-04 | failed | 4 | 1 | 3 | |
| 41 | +| 2019-01-05 | failed | 5 | 2 | 3 | |
| 42 | +| 2019-01-06 | succeeded | 6 | 4 | 2 | |
0 commit comments