这是我的桌子T1
dat_dt credit debit
-------- ------ -----
22-02-2019 10 5
25-02-2019 30 60
10-03-2019 50 40
13-03-2019 100 10
我想生成以下输出
max_date cr_sum progressive credit dr_sum progressive debit
-------- ------ ------------------ ------ -----------------
25-02-2019 40 40 65 65
13-03-2019 150 190 50 115
我想计算每个月的贷方和借方之和,累进贷方是在该月的贷方总和加上上个月的累进贷方的列。对于累进借记也是如此。 max_date是每个月的最大日期。除了使用循环之外,是否有任何简单的方法来获取此输出?
答案 0 :(得分:1)
您可以在下面尝试-
select max(dat_date) as max_date,sum(credit) as cr_sum,
sum(credit) over(order by EXTRACT(month FROM dat_date),EXTRACT(year FROM dat_date)) as progressive_credit,
sum(debit) as dr_sum,
sum(debit) over(order by EXTRACT(month FROM dat_date),EXTRACT(year FROM dat_date)) as progressive_debit
group by EXTRACT(month FROM dat_date),EXTRACT(year FROM dat_date)
答案 1 :(得分:1)
您似乎想要一个累加的总和,但按月汇总:
select max(dat_dt) as dat_dt,
sum(credit) as credit,
sum(sum(credit)) over (order by min(dat_dt)) as running_credit,
sum(debit) as debit,
sum(sum(debit)) over (order by min(dat_dt)) as running_debit
from t1
group by to_char(dat_dt, 'YYYY-MM')
order by min(dat_dt);
Here是db <>小提琴。
答案 2 :(得分:1)
您可以使用以下查询
with t1( dat_dt, credit, debit) as
(
select date'2019-02-22',10, 5 from dual union all
select date'2019-02-25',30, 60 from dual union all
select date'2019-03-10',50, 40 from dual union all
select date'2019-03-13',100,10 from dual
)
select max(dat_dt) as "max date",
sum(credit) as "cr sum",
sum(sum(credit)) over ( order by to_char(dat_dt,'yyyymm') ) as "progressive credit",
sum(debit) as "dr sum",
sum(sum(debit)) over ( order by to_char(dat_dt,'yyyymm') ) as "progressive debit"
from t1
group by to_char(dat_dt,'yyyymm')
order by to_char(dat_dt,'yyyymm');
按年月组合汇总。