Поскольку вы не можете использовать отсортированные оконные агрегаты для генерации итогов, вы можете сделать это без логики sub-select
или non-equijoin через self- join
и cross apply
:
declare @t table(ValueName varchar(10),ValueDate date, ValueAmount int);
insert into @t values
('Name 1','20190101',4)
,('Name 1','20190102',3)
,('Name 1','20190103',8)
,('Name 1','20190104',6)
,('Name 1','20190105',9)
,('Name 1','20190106',6)
,('Name 1','20190107',3)
,('Name 1','20190108',2)
,('Name 1','20190109',1)
,('Name 2','20190101',3)
,('Name 2','20190102',7)
,('Name 2','20190103',6)
,('Name 2','20190104',8)
,('Name 2','20190105',8)
,('Name 2','20190106',7)
,('Name 2','20190107',6)
,('Name 2','20190108',9)
,('Name 2','20190109',3);
select t.ValueName
,t.ValueDate
,t.ValueAmount
,t.ValueAmount + isnull(sum(p.ValueAmount),0) as SevenDayTotal
from @t as t
cross apply(values(dateadd(day,-1,t.ValueDate))
,(dateadd(day,-2,t.ValueDate))
,(dateadd(day,-3,t.ValueDate))
,(dateadd(day,-4,t.ValueDate))
,(dateadd(day,-5,t.ValueDate))
,(dateadd(day,-6,t.ValueDate))
) as d(d)
left join @t as p
on t.ValueName = p.ValueName
and p.ValueDate = d.d
group by t.ValueName
,t.ValueDate
,t.ValueAmount
order by t.ValueName
,t.ValueDate;
Выход
+-----------+------------+-------------+---------------+
| ValueName | ValueDate | ValueAmount | SevenDayTotal |
+-----------+------------+-------------+---------------+
| Name 1 | 2019-01-01 | 4 | 4 |
| Name 1 | 2019-01-02 | 3 | 7 |
| Name 1 | 2019-01-03 | 8 | 15 |
| Name 1 | 2019-01-04 | 6 | 21 |
| Name 1 | 2019-01-05 | 9 | 30 |
| Name 1 | 2019-01-06 | 6 | 36 |
| Name 1 | 2019-01-07 | 3 | 39 |
| Name 1 | 2019-01-08 | 2 | 37 |
| Name 1 | 2019-01-09 | 1 | 35 |
| Name 2 | 2019-01-01 | 3 | 3 |
| Name 2 | 2019-01-02 | 7 | 10 |
| Name 2 | 2019-01-03 | 6 | 16 |
| Name 2 | 2019-01-04 | 8 | 24 |
| Name 2 | 2019-01-05 | 8 | 32 |
| Name 2 | 2019-01-06 | 7 | 39 |
| Name 2 | 2019-01-07 | 6 | 45 |
| Name 2 | 2019-01-08 | 9 | 51 |
| Name 2 | 2019-01-09 | 3 | 47 |
+-----------+------------+-------------+---------------+