2015-02-23 105 views
2

我已經搜索,但沒有找到任何適合我的東西。我有3張桌子。一個是客戶機Id名稱查找,一個支付表和一個invloice表。每位客戶都有一張或多張發票記錄,其中有欠款。客戶在支付表中有0個或更多記錄。付款可能用於多張發票,也可能有多張付款用於一張發票。我想得到每個客戶的欠款總額。例如,爲每個客戶添加所有發票並減去每個客戶的所有付款。Mysql減去發票付款

Invoices    Payments     Clients 
-------------------- ------------------  ----------- 
|Id|ClientId|Amount| |Id|ClientId|Paid|  |Id| Name | 
|1 | 3 | 200 | | 1| 2  | 10 |  | 1| Bob | 
|2 | 2 | 10 | | 2| 1  | 20 |  | 2| Tom | 
|3 | 4 | 100 | | 3| 2  | 100|  | 3| John | 
|4 | 2 | 240 | | 4| 3  | 240|  | 4| Peter | 
| 5| 1 | 20 | ------------------  -------------- 
-------------------- 

Expected Result 
---------------------- 
|Name |Spent|Paid|Total| 
|John | 200 | 240| -40| 
| Tom | 250 | 110| 140 | 
|Peter| 100 | 0| 100 | 
| Bob | 20 | 20| 0 | 
------------------------ 
+0

這是一個暗示:從發票組'選擇(選擇總和(金額)通過clientid)作爲「花費」,(從支付組中選擇總額(金額),作爲「支付」等) – ITroubs 2015-02-23 11:12:37

回答

2

考慮以下幾點:

DROP TABLE IF EXISTS invoices; 

CREATE TABLE invoices 
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY 
,client_id INT NOT NULL 
,amount DECIMAL(5,2) NOT NULL 
); 

INSERT INTO invoices VALUES 
(1,3,200), 
(2,2, 10), 
(3,4,100), 
(4,2,240), 
(5,1, 20); 

DROP TABLE IF EXISTS payments; 

CREATE TABLE payments 
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY 
,client_id INT NOT NULL 
,paid DECIMAL(5,2) 
); 

INSERT INTO payments VALUES 
(1,2,10), 
(2,1,20), 
(3,2,100), 
(4,3,240); 

DROP TABLE IF EXISTS clients; 

CREATE TABLE clients 
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY 
,name VARCHAR(12) NOT NULL 
); 

INSERT INTO clients VALUES 
(1,'Bob'), 
(2,'Tom'), 
(3,'John'), 
(4,'Peter'); 

SELECT c.name 
    , SUM(CASE WHEN x.type = 'invoice' THEN x.amount ELSE 0 END) spent 
    , SUM(CASE WHEN x.type = 'payment' THEN x.amount ELSE 0 END) paid 
    , SUM(CASE WHEN x.type = 'invoice' THEN x.amount ELSE x.amount * -1 END) total 
    FROM clients c 
    JOIN 
    (SELECT client_id 
      , 'invoice' type 
      , amount 
     FROM invoices 
     UNION 
     SELECT client_id 
      , 'payment' 
      , paid 
     FROM payments 
    ) x 
    ON x.client_id = c.id 
GROUP 
    BY c.id; 

+-------+--------+--------+--------+ 
| name | spent | paid | total | 
+-------+--------+--------+--------+ 
| Bob | 20.00 | 20.00 | 0.00 | 
| Tom | 250.00 | 110.00 | 140.00 | 
| John | 200.00 | 240.00 | -40.00 | 
| Peter | 100.00 | 0.00 | 100.00 | 
+-------+--------+--------+--------+ 

要看到這是如何工作的,請嘗試執行剛子查詢位SELECT client_id... FROM payments

+0

當我在我的表上使用select時,結果不正確。一個客戶有3筆支付記錄,共計7000個發票和3個記錄在發票中,總計7000個發票中有21000個結果,付款21000個結果 – Dave 2015-02-23 11:48:23

+0

做出更改 - 仍然與更改前完全相同。 – Dave 2015-02-23 12:00:29

+0

*應該*現在就可以了! – Strawberry 2015-02-23 12:19:50