简体   繁体   中英

How to get the Outstanding balance using debit credit

I want to get the outstanding balance for all contractors and vendors using debit credit, but the problem is there are multiple document number so i cant relate them with debit-credit to become balance.

I tried relating the cdvno but the problem is there were multiple entry so is there possible way to relate them with each other

SELECT b.amount,a.cdvno, a.debit, a.credit, a.Debit + a.Credit - b.amount 'balance'
    FROM cdvdtl a left join
         cdvhdr b
         on b.cdvno = a.cdvno and b.trantype = a.trantype

i want the result to be like this if possible with only 1 cdvno output

amount          cdvno           debit      credit      balance
15000.00    000-2016-02000009   0.00       15000.00 0.00
15000.00    000-2016-02000009   15000.00    0.00    0.00

but the result is like this

amount  cdvno              debit    credit  balance
596.64  000-2016-01000617   0.00    596.64  0.00
596.64  000-2016-01000617   0.00    6.03    -590.61
596.64  000-2016-01000617   602.67  0.00    6.03

sample data in my table1 cdvdtl cdvhdr debit credit

I don't understand the logic behind the [amount] column as it seems not following the math running on debit nor credit.

But one way to tickle your situation of scattering debit and credit could be using group by

    select amount, cdvno, sum(debit) as [debit], sum(credit) as [credit],sum(balance) as [balance] from [tablename] group by cdvno

If I'm understanding correctly, here's one solution using union all to separate the records and get 2 rows per cdvno with a debit balance and a credit balance.

select a.cdvno, a.debit, a.credit, a.credit + a.debit - coalesce(b.bamount,0)
from (
    select cdvno, debit, sum(credit) credit, trantype
    from cdvdtl  
    where debit = 0
    group by cdvno, debit, trantype
    union all
    select cdvno, sum(debit) debit, credit, trantype
    from cdvdtl  
    where credit = 0
    group by cdvno, credit, trantype
) a left join cdvhdr b
     on b.cdvno = a.cdvno and b.trantype = a.trantype

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM