Reputation: 35
I've been stuck on this one for quite some time now and I can't figure it out.
Here's my problem:
I have two boolean columns condition_1
and condition_2
, and I want to create a third column inc
where the value increments each time this condition if condition_2 is false and lead(condition_1) over(partition by column_x order by column_y) is false
is met.
The result would look something like that:
column_x column_y condition_1 condition_2 inc
A 12/03/2020 true true 1
A 13/03/2020 true false 1
A 14/03/2020 false false 2
A 15/03/2020 false true 3
A 16/03/2020 true false 3
A 17/03/2020 false true 4
Doing something like
if(condition_2 is false and lead(condition_1) over(partition by column_x order by column_y) is false, lag(inc) over(partition by column_x order by column_y) + 1, lag(inc) over(partition by column_x order by column_y)) inc
obv doesn't work since inc
doesn't yet exist at the time of the query, and doing
if(condition_2 is false and lead(condition_1) over(partition by column_x order by column_y) is false, + 1, + 0) inc
won't be incremental as it will reset to 0 for each row.
Does someone have an idea?
Thanks a lot!
Upvotes: 0
Views: 925
Reputation: 1269823
You describe this formula:
select t.*,
countif( (not condition_2) and (not next_1)) over (partition by column_x order by column_y)
from (select t.*,
lead(condition_1) over (partition by column_x order by column_y) as next_1
from t
) t;
If you want the numbers to start at 1, then you need to add "1" to the value.
Upvotes: 1