在Postgresql

时间:2018-11-12 06:27:15

标签: sql postgresql

我正在尝试在postgresql查询中设置期初和余额列,在其中我输入特定的日期范围,并且每个日期明智行中的首次期初数据应为开始日期,余额应为(期初数据+借方-贷方)。 / p>

***这是我的示例数据库名称“ opening_and_closing”

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中的预期查询 * 日期范围是2017年3月1日至2017年6月1日

                                    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

1 个答案:

答案 0 :(得分:0)

***在数据库中创建一个名为“ opening_and_closing”的表

create table opening_and_closing (date1 date, acc_no varchar(250), debit numeric,credit numeric);

***在“ opening_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
相关问题