【问题标题】:SQL populating leading rows with conditionsSQL 使用条件填充前导行
【发布时间】:2021-02-24 21:34:31
【问题描述】:

我有一张像下面这样的表格

如果condition 列被填充,那么对于该行之后的所有行,如果other condition 列包含xepisode startepisode end,则使用值flag 填充列episode endcondition 列包含yes 的较早最近的行

最终输出:

index   name    condition   episode_start   Episode_end other_condition  value     new
1         a                           11       12           
2         a                            1        2           
3         a          yes               1        2           
4         a                            1        2           
5         a                            1        2              x          f       flag
6         a                            3        4              b          cc    

#update1 下面建议的答案有效。

但不确定如何进行此更改

在当前情况下,我们正在寻找列 condition=yes 之后的行中的特定条件

有没有办法查看当前行之后的行,而不是查看前一行?

【问题讨论】:

    标签: sql tsql sql-order-by case window-functions


    【解决方案1】:

    如果我没看错,你可以使用窗口函数:

    select t.*,
        case when other_condition = 'x'
            and max(condition) over(partition by episode_start, episode_end order by index) is not null
        then 'flag'
        end as newcol
    from mytable t
    

    一旦遇到非null condition,此标志所有后续行都具有相同的episode_startepisode_end 以及other_condition 中的非null 值。

    【讨论】:

    • 您如何检查condition 列是否填充在当前行之前的一行中?
    • 有没有办法检查condition 列是否填充了yes 而不是not null
    • @user2543622:最大窗口可以做到这一点。由于order by 子句,只考虑前面的行(直到当前行,包括在内)。
    • @user2543622:所以,and max(...) over(...) = 'yes'
    • 窗口最大功能是否工作,因为我们一次处理一行?
    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2015-05-21
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多