【问题标题】:How to calculate debit and credit balance in SQL Server?如何在 SQL Server 中计算借方和贷方余额?
【发布时间】:2019-03-06 03:29:37
【问题描述】:

我有桌子:

  • 客户(Id_Customer、姓名、地址)

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

       (2, 10)
       (3, 20)
       (2, 15)
    
  • 付款(Id_Customer、Money)

       (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

注意,仅当借方余额或贷方余额不为零时才显示客户。并且 Totals over () 用于分页。

我使用 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

【问题讨论】:

    标签: sql sql-server-2012


    【解决方案1】:

    修改后的查询。 (抱歉耽搁了)

    以下内容应该可以满足您的需求

    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
    

    【讨论】:

    • 我认为上面的查询不会给出最后一行的总余额
    • 亲爱的 Smart003!我使用 QUERY 运行,但只显示在收据和付款两个表中也有“钱”的客户(如果客户在收据中只有钱,或者付款不会显示在结果中,为什么会这样?它不能显示顾客???)
    • Luv,会在这个答案的正文中添加一些解释,解释你是如何解决这个问题的?这对 OP 和可能希望从中学习的未来读者都有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多