我搜索过但没找到任何对我有用的东西。我有3张桌子。一个是客户端ID名称查找,支付表和一个invloice表。每个客户都有1个或多个发票记录,其中包含欠款。客户在付款表中有0个或更多记录。付款可能针对多张发票,或者一张发票可能有多笔付款。我想得到每个客户的欠款。例如,为每个客户添加所有发票,并减去每个客户的所有付款。
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 :(得分: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