SQL - 添加所有以前的列和当前列,没有滞后和超前

SQL - Add all previous columns and current column without lag and lead

我有一个 table 喜欢

  ID      YEAR    VALUE  
  ----------------------
  1       2017    1
  1       2018    8
  1       2019    0
  1       2020    6
  1       2021    2

我正在尝试将所有前一行 VALUE 列值添加到当前行 VALUE 列值并显示总计。我的结果应该是这样的:

  ID      YEAR    VALUE  TOTAL
  ----------------------------
  1       2017    1      1
  1       2018    8      9
  1       2019    0      9
  1       2020    6      15
  1       2021    2      17

我尝试使用 join 和 row_number 来获取此信息,但 2019 年的 0 值搞砸了。

 select *, row_number() over (partition by ID order by YEAR) as RN
 into #t1
 from tbl

 select 
    t1.VALUE + ISNULL(t2.VALUE, 0),
    t1.*
from #t1 as t1
left join #t1 as t2 on t2.ID = t1.ID and (t2.RN + 1) = t1.RN

我通过此查询获得的结果是:

  ID      YEAR    VALUE  TOTAL
  ----------------------------
  1       2017    1      1
  1       2018    8      9
  1       2019    0      8
  1       2020    6      6
  1       2021    2      8

有什么帮助吗?

您需要 window 功能:

select t.*, sum(t.[value]) over (partition by t.id order by t.[year]) as total
from #t1 t;

如果您想要一个类似于您尝试过的解决方案:

select *, row_number() over (partition by ID order by YEAR) as RN
into #t1
from tablename;

select
  t.id, t.year, t.value, sum(#t1.value) TOTAL
from tablename t inner join #t1
on #t1.id = t.id and #t1.year <= t.year
group by t.id, t.year, t.value;

或使用子查询计算 运行 总数:

select t.*,
  (select sum(value) from tablename where id = t.id and year <= t.year) TOTAL
from tablename t 

参见demo
结果:

> id | year | value | TOTAL
> -: | ---: | ----: | ----:
>  1 | 2017 |     1 |     1
>  1 | 2018 |     8 |     9
>  1 | 2019 |     0 |     9
>  1 | 2020 |     6 |    15
>  1 | 2021 |     2 |    17