簡體   English   中英

如何在SQL Server中計算借方和貸方余額?

[英]How to calculate debit and credit balance in SQL Server?

我有桌子:

  • 客戶(Id_Customer,姓名,地址)

      (1,A, Add1) (2,B, Add2) (3,C, Add3) (4,D, Add4) (5,E, Add5) 
  • 收據(Id_Customer,資金)

      (2, 10) (3, 20) (2, 15) 
  • 付款(Id_Customer,資金)

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

現在,我想顯示如下:

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

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

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

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


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

在那里面:

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

請注意,僅在“借方余額”或“貸方”不為零時顯示“客戶”。 並且總計超過()進行分頁。

我使用QUERY運行,但僅在兩個表中顯示“錢”的客戶收據和付款(如果客戶只有收據中有錢,否則付款不會顯示結果,為什么?不能顯示該客戶?)

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 ;

結果如下:

名稱-------借方余額------貸方

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

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

修改后的查詢。 (不好意思推遲了)

以下應滿足您的需求

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM