从分组结果中减去一行的值
Subtract the value of a row from grouped result
我有一个 table supplier_account,它有五个列 supplier_account_id(pk),supplier_id(fk),voucher_no,借方和贷方.我想获得按 supplier_id 分组的借方总和,然后减去 voucher_no 不为空的行的贷方值。因此,对于每个后续行,借方总和的值都会减少。我试过使用 'with' 子句。
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
但这里所有行的借记值都相同。在第一行中减去之后,我想在第二行中得到结果并从中减去下一个信用值。
我知道使用临时 tables 是可能的。问题是我不能使用临时 tables,因为该过程用于使用 Jasper Reports 生成报告。
您需要的是 运行 总数的实施。借助 window 函数最简单的方法:
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
结果:
| 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 |
我有一个 table supplier_account,它有五个列 supplier_account_id(pk),supplier_id(fk),voucher_no,借方和贷方.我想获得按 supplier_id 分组的借方总和,然后减去 voucher_no 不为空的行的贷方值。因此,对于每个后续行,借方总和的值都会减少。我试过使用 'with' 子句。
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
但这里所有行的借记值都相同。在第一行中减去之后,我想在第二行中得到结果并从中减去下一个信用值。
我知道使用临时 tables 是可能的。问题是我不能使用临时 tables,因为该过程用于使用 Jasper Reports 生成报告。
您需要的是 运行 总数的实施。借助 window 函数最简单的方法:
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
结果:
| 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 |