基于另一列增加一列的值

时间:2015-12-15 19:43:17

标签: sql sql-server

如何从Above图片生成bus_day_mtd列,它应该根据bus_day_flag = 1自动进行icremented,如果bus_day_flag = 0,它应该保持相同

2 个答案:

答案 0 :(得分:1)

update T
set bus_day_mtd = (
    select sum(bus_day) from T t2 where t2.ymd <= T.ymd
    --or cast(bus_day_flag as int) if referencing the bit column
)

您是否希望动态计算而不是静态列?

答案 1 :(得分:1)

在SQL Server 2012+中,您可以使用累积总和来执行此操作:

with toupdate as (
      select t.*,
             sum(case when bus_day_flag = 1 then bus_day end) over (order by ymd) as new_bus_day_mtd
      from t
     )
update toupdate
    set bus_day_mtd = new_bus_day_mtd;