SQL 与之前的结果合计
SQL aggregate with the previous result
我有以下table
Year1
Year2
Value
2014
2014
1
2014
2014
2
2014
2015
3
2014
2016
4
2015
2015
5
2015
2016
6
2015
2017
7
2015
2017
8
我需要写一个 SQL 查询来给我这个:
Year1
Year2
Value
2014
2014
3
2014
2015
6
2014
2016
10
2015
2015
5
2015
2016
11
2015
2017
26
group by 可以帮助对 year1 和 year2 进行分组,但我的问题是过去聚合的累积结果。
首先在您的组中聚合,然后使用窗口聚合:
WITH CTE AS(
SELECT Year1,
Year2,
SUM([Value]) AS [Value]
FROM dbo.YourTable
GROUP BY Year1,
Year2)
SELECT Year1,
Year2,
SUM([Value]) OVER (PARTITION BY Year1 ORDER BY Year2) AS [Value]
FROM CTE;
我有以下table
Year1 | Year2 | Value |
---|---|---|
2014 | 2014 | 1 |
2014 | 2014 | 2 |
2014 | 2015 | 3 |
2014 | 2016 | 4 |
2015 | 2015 | 5 |
2015 | 2016 | 6 |
2015 | 2017 | 7 |
2015 | 2017 | 8 |
我需要写一个 SQL 查询来给我这个:
Year1 | Year2 | Value |
---|---|---|
2014 | 2014 | 3 |
2014 | 2015 | 6 |
2014 | 2016 | 10 |
2015 | 2015 | 5 |
2015 | 2016 | 11 |
2015 | 2017 | 26 |
group by 可以帮助对 year1 和 year2 进行分组,但我的问题是过去聚合的累积结果。
首先在您的组中聚合,然后使用窗口聚合:
WITH CTE AS(
SELECT Year1,
Year2,
SUM([Value]) AS [Value]
FROM dbo.YourTable
GROUP BY Year1,
Year2)
SELECT Year1,
Year2,
SUM([Value]) OVER (PARTITION BY Year1 ORDER BY Year2) AS [Value]
FROM CTE;