I have a table (redshift db) with the following sample:
product_id | date | is_unavailable
1 | 1st Jan | 1
1 | 2nd Jan | 0
1 | 3rd Jan | 0
1 | 4rd Jan | 1
Here , a combination of date
and product_id
is unique
. I need to have a 4th column: "Days since last unavailable".
Here is the output required:
product_id | date | is_unavailable | days_since_last_unavailable
1 | 1st Jan | 1 | -
1 | 2nd Jan | 0 | 1
1 | 3rd Jan | 0 | 2
1 | 4rd Jan | 1 | 0
I thought of using lag
window function with partition over product_id
, however, an additional condition of unavailable_flag
has to be checked here which I cannot accommodate in my query.
select *, date-lag(date) over (partition by product_id order by date) as days_since_last_unavailbale from mytable order by product_id
However, I can't figure out how to use unavailable_flag since it is required to find the last date with unavailable_flag=1