I have problem with compare one date from partition by product_id. I need to check whether last date_to ordered by date_to desc is between date_from and date_to in range of dates.
Here's example of partition:
product_id | date_from | date_to
1 | 2017-01-01| 2019-05-01
1 | 2017-04-15| 2017-06-10
1 | 2017-03-15| 2017-03-25
1 | 2017-01-19| 2017-02-01
How can I check whether date in last row is between any range of date in partition by product_id. This order have to be intact. I tried to with LAG function but it will check only previous range, I tried with min(date_from) and max(date_to) even here will be problem because min is from first row and max from the second and the qualification is false because I need to check every range of dates by product not whole range. The solution will check:
*2017-02-01 between (first row of partition) 2017-01-01 and 2019-05-01 (TRUE)
*2017-02-01 between (second row of partition) 2017-04-15 and 2017-06-10 (FALSE)
*2017-02-01 between (third row of partition) 2017-03-15 and 2017-03-25 (FALSE)
Result: YES! The date is between some range of dates ;) OK just flag 1 will be enough :)
I will be grateful for any help you can provide and sorry for my english :)
EDIT: Current problem is how to check every date_to in order with previous range. E.g.
(second date_to) 2017-06-10 between (first row) 2017-01-01| 2019-05-01
(third date_to) 2017-03-25 between (first row) 2017-01-01| 2019-05-01 and (third date_to) 2017-03-25 between (second row) 2017-04-15| 2017-06-10
etc.