从分组结果中减去一行的值

时间:2015-06-04 05:15:19

标签: sql postgresql postgresql-9.3

我有一个表supplier_account,它有五个coloumns supplier_account_id(pk),supplier_id(fk),voucher_no,debit和credit。我想获取按supplier_id分组的借方总和,然后减去voucher_no不为空的行的贷方价值。因此,对于每个后续行,借方和的值减小。我尝试过使用'子句。

with debitdetails as(
select supplier_id,sum(debit) as amt
from supplier_account group by supplier_id
)
select acs.supplier_id,s.supplier_name,acs.purchase_voucher_no,acs.purchase_voucher_date,dd.amt-acs.credit as amount
from supplier_account acs
left join supplier s on acs.supplier_id=s.supplier_id
left join debitdetails dd on acs.supplier_id=dd.supplier_id
where voucher_no is not null

但是这里所有行的借方值都是相同的。在第一行中减去后,我想在第二行得到结果并从中减去下一个信用值。

我知道可以使用临时表。问题是我无法使用临时表,因为该过程用于使用Jasper Reports生成报告。

1 个答案:

答案 0 :(得分:1)

您需要的是运行总计的实现。借助窗口函数最简单的方法:

with debitdetails as(
select id,sum(debit) as amt
from suppliers group by id
)
select s.id, purchase_voucher_no, dd.amt, s.credit,
dd.amt - sum(s.credit) over (partition by s.id order by purchase_voucher_no asc)
from suppliers s
left join debitdetails dd on s.id=dd.id
order by s.id, purchase_voucher_no

SQL Fiddle

结果:

| id | purchase_voucher_no | amt | credit | ?column? |
|----|---------------------|-----|--------|----------|
|  1 |                   1 |  43 |      5 |       38 |
|  1 |                   2 |  43 |     18 |       20 |
|  1 |                   3 |  43 |      8 |       12 |
|  2 |                   4 |  60 |      5 |       55 |
|  2 |                   5 |  60 |     15 |       40 |
|  2 |                   6 |  60 |     30 |       10 |