简体   繁体   中英

SQL Query - Adding total amounts from multiple tables

I'm working on a project for a client and require the total sum of 3 different columns on 3 different tables where the status of these amounts is stated as "Cleared".

The three tables are (as an example):

PAYMENT1

ID | Amount | Status  
1  | 200    | Cleared

PAYMENT2

ID | Amount | Status              
1  | 100    | Cleared

PAYMENT3

ID | Amount | Status  
1  | 300    | Cleared

I have come up with the following code which does essentially what I want to achieve but the values that are getting processed are coming out being multiplied by three (when adding values from more than one table).

SELECT SUM(CASE WHEN P1.`Status` = "Cleared" THEN P1.Amount ELSE 0 END) 
     + SUM(CASE WHEN P2.`Status` = "Cleared" THEN P2.Amount ELSE 0 END)
     + SUM(CASE WHEN P3.`Status` = "Cleared" THEN P3.Amount ELSE 0 END) AS ClearedFunds
FROM PAYMENT1 As P1, 
     PAYMENT2 As P2, 
     PAYMENT3 As P3 ;

The query above would return (from the examples given): 1800 instead of the expected result of 600.

Can anyone find out what is going wrong?

SELECT  ID, SUM(Amount) totalAmount
FROM
    (
        SELECT  ID, Amount
        FROM    payment1
        WHERE   Status = 'Cleared'
        UNION ALL
        SELECT  ID, Amount
        FROM    payment2
        WHERE   Status = 'Cleared'
        UNION ALL
        SELECT  ID, Amount
        FROM    payment3
        WHERE   Status = 'Cleared'
    ) s
GROUP   BY ID

您可以将Union All与三个select查询一起使用,以将结果作为一个表获得,然后使用sum合计函数获取状态已清除的金额之和。

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