简体   繁体   中英

How to calculate debit and credit balance in SQL Server?

I have tables:

  • Customer (Id_Customer, Name, Address)

      (1,A, Add1) (2,B, Add2) (3,C, Add3) (4,D, Add4) (5,E, Add5) 
  • Receipt (Id_Customer, Money)

      (2, 10) (3, 20) (2, 15) 
  • Payment (Id_Customer, Money)

      (1, 30) (2, 40) (4, 05) 

Now, I want to show as below:

Name   -------   Debit balance  ------    In credit    
A       ----------------------------------------30

B ----------------15-------------------------

C    -----------------------------------------20

D  -------------- 05-----------------------


Total DB: -----   20-------------Total IC: 50

In that:

if sum(money) of Receipt < sum(money) of Payment 
   then Debit balance = sum(money) of Payment - sum(money) of Receipt 
else 
   In credit = sum(money) of Receipt-sum(money) of Payment

Note, only show Customer if Debit balance OR In credit is different from zero. And Totals over () for paging.

I run with QUERY, but ONLY show the Customers that also have 'money' in two tables Receipt and Payment (if customer only have money in Receipt OR Payment will don't show in result, why is that? Can it not show that customer?)

select a.*, Total_DebitBalance=sum(DebitBalance) over (), Total_InCredit=sum(InCredit) over () from (SELECT C.name, C.Address,

CASE WHEN SUM(isnull(R.Money, 0))< SUM(isnull(P.Money, 0)) THEN SUM(isnull(P.Money, 0)) - SUM(isnull(R.Money, 0)) END AS DebitBalance,

CASE WHEN SUM(isnull(R.Money, 0))> SUM(isnull(P.Money, 0)) THEN SUM(isnull(R.Money, 0)) - SUM(isnull(P.Money, 0)) END AS InCredit,

C.Id_Customer, COUNT(*) OVER () AS total_count

FROM Customer C LEFT JOIN Receipt R ON C.Id_Customer = R.Id_Customer LEFT JOIN Payment P ON C.Id_Customer = P.Id_Customer group by C.Id_Customer, C.name, C.Address)a ;

This is the result:

Name ------- Debit balance ------ In credit

B ----------------15-------------------------

Total DB: -----   15-------------Total IC: 0

Modified Query. (Sorry for delay)

The below should serve your need

SELECT 
    C.Id_Customer,
    CASE 
       WHEN ISNULL(R.[Money], 0) - ISNULL(P.[Money], 0)> 0 
          THEN ISNULL(R.[Money], 0) - ISNULL(P.[Money], 0)
    END AS [Debit balance],
    CASE 
       WHEN ISNULL(P.[Money], 0) - ISNULL(R.[Money], 0) > 0 
          THEN ISNULL(P.[Money], 0) - ISNULL(R.[Money], 0)
    END AS [In credit]

FROM
    Customer C
LEFT JOIN 
    (SELECT SUM([Money]) AS [Money],Id_Customer FROM Receipt GROUP BY Id_Customer) R ON C.Id_Customer = R.Id_Customer
LEFT JOIN 
    (SELECT SUM([Money]) AS [Money],Id_Customer FROM Payment GROUP BY Id_Customer)P ON C.Id_Customer = P.Id_Customer

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