Вы можете использовать метод грубого O (n 2 ) самостоятельного соединения таблицы с самим собой, или, если таблица большая, лучше итеративно рассчитать баланс.Выбор для SQL Server 2000 ограничен, но в подходе, который я покажу, используется цикл, который пересекает таблицу в порядке date, transid
, а не курсоры.
Вот пример таблицы для обсуждения
create table trans (transid int identity, date datetime, inwards decimal(12,2), outward decimal(12,2))
insert trans select '20110203', null, 100
insert trans select '20100412', null, 200
insert trans select '20110203', 400, null -- !same date as first
Это пакет T-SQL, который даст вам требуемый вывод.Если вы просто хотели обновить столбец баланса в таблице (если у него был такой дополнительный столбец), измените все ссылки на #trans на саму таблицу.
-- fill a temp table with the new column required
select *, cast(null as decimal(12,2)) as balance
into #trans
from trans
-- create an index to aid performance
create clustered index #cix_trans on #trans(date, transid)
-- set up a loop to go through all record in the temp table
-- in preference to using CURSORs
declare @date datetime, @id int, @balance decimal(12,2)
select top 1 @date = date, @id = transid, @balance = 0
from #trans
order by date, transid
while @@ROWCOUNT > 0 begin
update #trans set @balance = balance = @balance + coalesce(inwards, -outward)
where transid = @id
-- next record
select top 1 @date = date, @id = transid
from #trans
where (date = @date and transid > @id)
or (date > @date)
order by date, transid
end
-- show the output
select *
from #trans
order by date, transid
;
-- clean up
drop table #trans;
Выходные данные
2 2010-04-12 00:00:00.000 NULL 200.00 -200.00
1 2011-02-03 00:00:00.000 NULL 100.00 -300.00
3 2011-02-03 00:00:00.000 400.00 NULL 100.00
РЕДАКТИРОВАТЬ
Если вам нужно показать окончательный результат, используя дату в формате дд / мм / гггг, используйте эту
-- show the output
select transid, convert(char(10), date, 103) date, inwards, outward, balance
from #trans
order by #trans.date, transid
;