2013-11-26 37 views
0

我創建了一個包含名稱和電話號碼(用戶)的用戶表。MySQL從同一個表中提取數據,SUM條件爲多個列

id| name | phone 

1 | Frank | 0345221234 
2 | Sara | 0342555939 

我保存日誌與用戶的呼叫不同號碼的另一個表(call_logs):

number  | destination | price 

0345221234 | destination | x    /// This is Frank 
0345221234 | destination | y    /// This is also Frank 
0342555939 | destination | z    /// This is Sara 

然後,我有認爲,弗蘭克和莎拉被允許呼叫號碼(表allowed_numbers):

number 

033485733 
045727728 
082358288 

我想通過我的用戶表圈和基於它們的數目來檢查電話記錄表並選擇的SUM 0列的日誌記錄,其中destination與允許的數字表不匹配,以便我知道不在允許列表中的呼叫的成本。

然後我想選擇priceSUM日誌記錄,其中destination確實匹配 允許的數字表,以便我知道沒有允許調用多少錢。

有什麼辦法,我可以與子查詢單查詢,做到這一切需要爲了實現這個結果集:

users number | SUM(price) of allowed calls | SUM(price) of calls not allowed 

謝謝!

+0

你能明確告訴我們表名是什麼嗎?我假設'users','call_logs','allowed_numbers'很可能是錯誤的。 –

+0

對不起,編輯! –

回答

2
SELECT call_logs.number 
    ,SUM(IF(allowed_numbers.number IS NOT NULL,call_logs.price,0)) AS AllowedPrice 
    ,SUM(IF(allowed_numbers.number IS NULL,call_logs.price,0)) AS NotAllowedPrice 
FROM call_logs 
LEFT JOIN allowed_numbers 
    ON call_logs.destination = allowed_numbers.number 
GROUP BY call_logs.number; 
+0

它看起來不錯!是否有任何方法來從日誌表中SUM另一個字段?類似每個允許的會話的持續時間字段和不允許的會話字段。謝謝! –

+1

感謝您的編輯,Alex W :) –

+1

@MannyCalavera - 您可以繼續在SELECT子句中添加其他字段,例如'SUM(call_logs.duration)'或'SUM(IF(allowed_numbers.number IS NULL,call_logs.duration, 0))' – AgRizzo

相關問題