SQL - Return 运行 总数(使用最新的总数)

SQL - Return the Running Total (using the latest total number)

假设我下面有一个table

ID   SUB_ID   YEAR  Month  Value
A1   A101      1      1     100
A1   A101      1      2     100
A1   A101      2      1     100
A1   A101      2      2     100
B1   B101      1      1     200
B1   B101      1      2     200
B1   B101      2      1     200
B1   B101      2      2     200
B1   B102      2      1     300  (So this B102 is a new record starting in YEAR 2 MONTH 1)
B1   B102      2      2     300

我想使用最新的总数得到每个 ID 的 运行 总和。输出应该是:

ID  YEAR  RUNNING_SUM
A1    1      100 
A1    2      100 (for A1, there is no value change or no new SUB_ID, so the sum is always 100)
B1    1      200
B1    2      500 (in YEAR 2, B102 was added)

我们怎样才能做到这一点?基本上,如果有新的 SUB_ID 进来,我会附加每个 ID 的值。这在 Tableau 中使用 LOD 计算(固定 ID)

很容易

这里是SQLFiddle(http://sqlfiddle.com/#!18/95b63d/1)

谢谢!

我想你只需要 row_number() 和聚合:

select id, year, sum(value)
from (select t.*,
             row_number() over (partition by id, sub_id, year order by month desc) as seqnum
      from t
     ) t
where seqnum = 1
group by id, year