I have a table of customer visits.
For each each customer, I want to compare the first record's post_vst_dt
to the vst_beg_dt
of the second record.
If the second visit record's vst_beg_dt
is greater than the first record's post_vst_dt
then the both records need to be selected else the first record's post_vst_dt
has to be compared to the third record's vst_beg_dt
.
Based on the same conditional check either both the first and third record has to be selected or just the first record.
This needs to be checked for all customers and each customer can have any number of visits.
Can this be accomplished using SQL or a mysql procedure with loop and cursor be use. Can someone help please.
| Visit_ID | Cust_ID | Vst_Beg_Dt | Vst_End_Dt | Post_vst_Dt |
|----------+---------+------------+------------+-------------|
| 445 | 545 | 2015-11-23 | 2015-11-28 | 2016-01-12 |
| 198 | 545 | 2016-01-07 | 2016-01-12 | 2016-02-26 |
| 271 | 545 | 2016-01-19 | 2016-01-29 | 2016-03-14 |
| 841 | 291 | 2015-09-08 | 2015-09-12 | 2015-10-27 |
| 987 | 291 | 2015-12-19 | 2015-12-23 | 2016-02-06 |
| 211 | 291 | 2015-12-26 | 2016-01-06 | 2016-02-20 |
| 122 | 291 | 2016-02-25 | 2016-02-27 | 2016-04-12 |
The expected output is
| Visit_ID | Cust_ID | Vst_Beg_Dt | Vst_End_Dt |
|----------+---------+------------+------------|
| 445 | 545 | 2015-11-23 | 2015-11-28 |
| 271 | 545 | 2016-01-19 | 2016-01-29 |
| 841 | 291 | 2015-09-08 | 2015-09-12 |
| 987 | 291 | 2015-12-19 | 2015-12-23 |
| 122 | 291 | 2016-02-25 | 2016-02-27 |
By 'first', I mean the record with the min vst_beg_dt, per customer