簡體   English   中英

MySQL SUM 兩列然后另一列與凈額

[英]MySQL SUM two columns then another column with the net amount

嗨,我嘗試了堆棧溢出的所有解決方案,但無濟於事

我有 2 個帶有 ID 主鍵的表,然后是日期和金額。 表中可以有多個相同日期的日期。 借方在借方表中使用負數

table "credits" 

id | date | amount
1   2020-01-01  10.00
2   2020-01-02  20.00
3   2020-01-03  30.00
4   2020-01-01  10.00
5   2020-01-02  10.00
6   2020-01-03  10.00

table "debits"

id  |  date | amount
55   2020-01-01  -5.00
56   2020-01-02  -5.00
57   2020-01-03  -5.00
58   2020-01-01  -5.00
59   2020-01-02  -5.00
60   2020-01-03  -5.00

我想像這樣返回一個 3 列結果,按 DATE 分組,包含 4 個字段、日期、貸方金額(當天)、借方金額(當天)和總金額(當天)

date | amount_credits | amount_debits | amount_total
2020-01-01    20    10    10
2020-01-02    30    10    20
2020-01-03    40    10    30

我會在日期對兩個表進行分組,然后加入這兩個表:

SELECT c.date, amount_credits, amount_debits, amount_credits - amount_debits AS amount_total
FROM   (SELECT   date, SUM(amount) AS amount_credits
        FROM     credits
        GROUP BY date) c 
JOIN   (SELECT   date, -1 * SUM(amount) AS amount_debits
        FROM     debits
        GROUP BY date) d ON c.date = d.date

我會使用union all和 aggrgtion 來做到這一點:

select date, sum(credit) as credits, abs(sum(debits)) as debits),
       sum(credits) + sum(debits) as net
from ((select c.date, c.amount as credit, 0 as debit
       from credits c
      ) union all
      (select c.date, 0, d.amount
       from debits d
      )
     ) cd
group by date;

我注意到借方金額的符號從源表到結果集發生了變化,這就是外部查詢使用abs()的原因。

特別是,使用union allgroup by可以確保原始數據中的所有日期都在結果集中——即使日期只在一個表中。

暫無
暫無

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

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