*** Создайте имя таблицы "creation_and_closing" в вашей базе данных
create table opening_and_closing (date1 date, acc_no varchar(250), debit numeric,credit numeric);
*** Вставьте значения в вашу таблицу «creation_and_closing»
insert into opening_and_closing
values ('2017-01-01','a',500,0),
('2017-01-02','a',0,400),
('2017-01-03','a',100,0),
('2017-01-04','a',800,0),
('2017-01-05','a',0,700),
('2017-01-06','a',800,0),
('2017-01-01','b',500,0),
('2017-01-02','b',0,400),
('2017-01-03','b',100,0),
('2017-01-04','b',800,0),
('2017-01-05','b',0,700),
('2017-01-06','b',800,0);
*** Теперь выполните следующий запрос
select date1,acc_no,opening,debit,credit,
(opening+sum(debit-credit) OVER (partition by acc_no order by date1)) as balance
from
(select date1,acc_no,debit,credit,
(select sum(debit)-sum(credit) from opening_and_closing where date1 < '2017-01-03' and acc_no ='a') as opening
from opening_and_closing
where date1 between '2017-01-03' and '2017-01-06'
and acc_no ='a'
group by 1,2,3,4
order by date1)x