[英]Opening and Balance amount query for different account in postgresql
我正在嘗試在 postgresql 查詢中設置開盤和余額列,其中我輸入特定的日期范圍,第一個開盤數據應該是開始日期,並且每個日期行中的余額應該是(開盤數據 + 借記 - 貸記)。
*** 這是我的示例數據庫名稱“opening_and_closure”
date1 acc_no debit credit
01/01/2017 a 500 0
02/01/2017 a 0 400
03/01/2017 a 100 0
04/01/2017 a 800 0
05/01/2017 a 0 700
06/01/2017 a 800 0
01/01/2017 b 500 0
02/01/2017 b 0 400
03/01/2017 b 100 0
04/01/2017 b 800 0
05/01/2017 b 0 700
06/01/2017 b 800 0
* 我在 postgresql 中的預期查詢 *日期范圍是 03/01/2017 到 06/01/2017
opening : 100
date1 acc_no debit credit balance
03/01/2017 a 100 0 200
04/01/2017 a 800 0 1000
05/01/2017 a 0 700 300
06/01/2017 a 800 0 1100
opening : 100
date1 acc_no debit credit balance
03/01/2017 b 100 0 200
04/01/2017 b 800 0 1000
05/01/2017 b 0 700 300
06/01/2017 b 800 0 1100
***在您的數據庫中創建一個表名“opening_and_closure”
create table opening_and_closing (date1 date, acc_no varchar(250), debit numeric,credit numeric);
***在“opening_and_closed”表中插入值
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.