2013-01-09 65 views
1

這將很難解釋。MySQL - 查詢內部的複雜SUMs

我正在循環瀏覽從tbl_customers我的客戶記錄一天幾次。

SELECT c.* FROM tbl_customers c 

我回國只是客戶的:customeridnamephoneemail

現在怪異的一部分。 我想追加3列,在電子郵件之後:totalpaid,totalowed,totalbalance 但是,那些列名不存在任何地方。

這是我如何查詢每一項:(作爲一個單一的查詢)

SELECT SUM(total) AS totalpaid 
FROM tbl_customers_bills 
WHERE customerid = X 
AND billtype = 1 

SELECT SUM(total) AS totalowed 
FROM tbl_customers_bills 
WHERE customerid = X 
AND billtype = 2 

SELECT SUM(total) AS totalbalance 
FROM tbl_customers_bills 
WHERE customerid = X 
AND billtype IN(1,2) 

所以,billtype是,告訴我該記錄是否繳納或者未列。

我在這裏不知所措。 如何將3個單獨的查詢合併到第一個查詢的循環中?

回答

5

只需加入客戶賬單,並做到這一點。分離出totalpaid和totalowed可以使用SUM(CASESUM(IFwless1's answer demonstrates

SELECT c.*, 
     SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid , 
     SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed , 
     SUM(total) AS totalbalance 
FROM 
    tbl_customers c 
    LEFT JOIN tbl_customers_bills b 
    ON c.customerid = b.customerid 
    and billtype in (1,2) 
GROUP BY 
    c.customerid 

因爲這是MySQL中,你只需要組客戶的PK。

3

你可以用GROUPSUM組合做到這一點,IF

SELECT c.id, c.name, c.phone, c.email, 
SUM(IF(b.billtype = 1, b.total, 0)) AS totalpaid, 
SUM(IF(b.billtype = 2, b.total, 0)) AS totalowed, 
SUM(IF(b.billtype = 1 OR b.billtype = 2, b.total, 0)) AS totalbalance, 
FROM tbl_customers c LEFT JOIN tbl_customers_bills b ON b.customerid = c.id 
GROUP BY c.id 

參見: http://dev.mysql.com/doc/refman/5.0/en//group-by-functions.html http://dev.mysql.com/doc/refman/5.0/en/control- flow-functions.html

+0

哎呀,對不起,忘了! – wless1