前 6 行的总和 SQL 服务器 2008
Sum of 6 previous rows SQL SERVER 2008
我有一个简单的查询:
Select
fiscalweek, 4171
From table
我按财政周的顺序得到结果:
FiscalWeek 4171
1 691
2 746
3 650
4 625
5 788
6 581
7 597
8 772
9 777
我想在第三列中显示前 6 个财政周的总和,或者第 2 周只是第 1 周和第 2 周的总和,
所以输出将是:
FiscalWeek 4171 Sum
1 691 691
2 746 1437
3 650 2087
4 625 2712
5 788 7671
6 581 4081
7 597 3393
8 772 4013
9 777 4140
我试过使用 rows unbounded preceeding
,但 2008 年不可用,有什么建议吗?
对于这种简单的情况,最简单的方法是自 table 非等值连接。假设 t
是您的 table,a
是财政周:
MS SQL Server 2014 架构设置:
create table t ( a int, t int);
insert into t values
(1,10),
(2,11),
(3,12),
(4,13),
(5,14),
(6,15),
(7,16),
(8,17),
(9,18),
(10,19),
(11,20),
(12,10);
查询 1:
select t1.a, t1.t, sum(t2.t)
from t t1
inner join t t2
on t2.a between t1.a-6 and t1.a --self non equijoin taking 6 prev.
group by t1.a, t1.t
order by t1.a
| a | t | |
|----|----|-----|
| 1 | 10 | 10 |
| 2 | 11 | 21 |
| 3 | 12 | 33 |
| 4 | 13 | 46 |
| 5 | 14 | 60 |
| 6 | 15 | 75 |
| 7 | 16 | 91 |
| 8 | 17 | 98 |
| 9 | 18 | 105 |
| 10 | 19 | 112 |
| 11 | 20 | 119 |
| 12 | 10 | 115 |
硬方法,可能更 sql XXI century friendly or not, is to deal with CTE, partitions and ranks.感兴趣的可以搜索一下。
我有一个简单的查询:
Select
fiscalweek, 4171
From table
我按财政周的顺序得到结果:
FiscalWeek 4171
1 691
2 746
3 650
4 625
5 788
6 581
7 597
8 772
9 777
我想在第三列中显示前 6 个财政周的总和,或者第 2 周只是第 1 周和第 2 周的总和,
所以输出将是:
FiscalWeek 4171 Sum
1 691 691
2 746 1437
3 650 2087
4 625 2712
5 788 7671
6 581 4081
7 597 3393
8 772 4013
9 777 4140
我试过使用 rows unbounded preceeding
,但 2008 年不可用,有什么建议吗?
对于这种简单的情况,最简单的方法是自 table 非等值连接。假设 t
是您的 table,a
是财政周:
MS SQL Server 2014 架构设置:
create table t ( a int, t int);
insert into t values
(1,10),
(2,11),
(3,12),
(4,13),
(5,14),
(6,15),
(7,16),
(8,17),
(9,18),
(10,19),
(11,20),
(12,10);
查询 1:
select t1.a, t1.t, sum(t2.t)
from t t1
inner join t t2
on t2.a between t1.a-6 and t1.a --self non equijoin taking 6 prev.
group by t1.a, t1.t
order by t1.a
| a | t | |
|----|----|-----|
| 1 | 10 | 10 |
| 2 | 11 | 21 |
| 3 | 12 | 33 |
| 4 | 13 | 46 |
| 5 | 14 | 60 |
| 6 | 15 | 75 |
| 7 | 16 | 91 |
| 8 | 17 | 98 |
| 9 | 18 | 105 |
| 10 | 19 | 112 |
| 11 | 20 | 119 |
| 12 | 10 | 115 |
硬方法,可能更 sql XXI century friendly or not, is to deal with CTE, partitions and ranks.感兴趣的可以搜索一下。