select * into #tab from (
select 1 as id, 'aa' as partner, 12 as part_no,
cast('2011-12-21' as datetime) as date, 40 as periode_sum union all
select 2, 'aa', 12, '2011-12-22', 30 union all
select 3, 'bb2', 13, '2011-12-22', 20 union all
select 4, 'bb2', 13, '2011-12-23', 30 union all
select 5, null, null, '2011-12-24', null union all
select 6, null, null, '2011-12-25', null union all
select 7, 'aa', 12, '2011-12-26', 30 union all
select 8, 'bb2', 13, '2011-12-27', 40
) t
select *, (select sum(periode_sum)
from #tab t1
where t1.partner = t.partner and t1.part_no = t.part_no
and t1.date < t.date and t1.id < t.id
) as previous_sum
from #tab t
Если разрешено более одной строки в день для конкретной пары (partner
, part_no
), тогда вместо and t1.date < t.date and t1.id < t.id
следует использовать and t1.date <= t.date and t1.id < t.id
. Вы можете использовать только and t1.id < t.id
, если id
обеспечивает правильный порядок (по времени) для всех строк.
Результат:
id partner part_no date periode_sum previous_sum
1 aa 12 2011-12-21 00:00:00.000 40 NULL
2 aa 12 2011-12-22 00:00:00.000 30 40
3 bb2 13 2011-12-22 00:00:00.000 20 NULL
4 bb2 13 2011-12-23 00:00:00.000 30 20
5 NULL NULL 2011-12-24 00:00:00.000 NULL NULL
6 NULL NULL 2011-12-25 00:00:00.000 NULL NULL
7 aa 12 2011-12-26 00:00:00.000 30 70
8 bb2 13 2011-12-27 00:00:00.000 40 50