2013-01-09 5 views
1

이것은 설명하기가 어렵습니다.MySQL - 쿼리 내의 복잡한 SUM

클라이언트 기록을 하루에 여러 번 tbl_customers에서 반복하고 있습니다.

SELECT c.* FROM tbl_customers c 

은 단순히 고객의 반환 해요 : customerid, name, phone, email

지금 이상한 부분. 전자 메일 : 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 레코드가 지불할지 여부를 알려줍니다 열은 다음과 같습니다

내가 하나 하나를 조회하는 방법입니다.

나는 여기를 잃고있다. 어떻게 SUM 3을 첫 번째 쿼리의 루프로 분리 할 수 ​​있습니까?

답변

5

그냥 고객을 청구서에 등록하고 합계를 계산하면됩니다. totalpaid을 분리하고이 만 고객의 PK에 그룹에 필요한 MySQL을하기 때문에 당신이 wless1'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 

SUM(CASE 또는 SUM(IF을 사용할 수 있습니다 totalowed합니다. 당신은 GROUP, SUM의 조합으로이 작업을 수행 할 수

3

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