简体   繁体   English

if 语句中满足条件时的增量值

[英]Incremental values when a condition is met in if statement

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.这是我的问题:我有两个布尔列condition_1condition_2 ,我想创建第三列incif condition_2 is false and lead(condition_1) over(partition by column_x order by column_y) is false每次此条件都会增加值遇到了。

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, 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 不起作用,因为inc在查询时尚不存在,并且正在执行

  • 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. if(condition_2 is false and lead(condition_1) over(partition by column_x order by column_y) is false, + 1, + 0) inc不会递增,因为每行都会重置为 0。

Does someone have an idea?有人有想法吗?

Thanks a lot!非常感谢!

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.如果您希望数字从 1 开始,则需要将“1”添加到值中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM