将列值添加到SQL中的下一列

时间:2018-05-31 10:34:42

标签: sql sql-server

我的sql表是

Week    Year    Applications
1       2017    0
2       2017    10
3       2017    20
4       2017    50
5       2017    0
1       2018    10
2       2018    0
3       2018    40
4       2018    50
5       2018    10

我希望SQL查询提供以下输出

Week    Year    Applications
1       2017    0
2       2017    10
3       2017    30
4       2017    80
5       2017    80
1       2018    10
2       2018    10
3       2018    50
4       2018    100
5       2018    110

任何人都可以帮我写下面的查询吗?

2 个答案:

答案 0 :(得分:2)

您可以使用SUM() OVER获取累积总和:

SELECT *, SUM(Applications) OVER(PARTITION BY Year ORDER BY Week)
FROM tab

答案 1 :(得分:1)

看起来你想要累积总和:

select week, year,
       sum(applications) over (partition by year order by week) as cumulative_applications
from t;