2016-07-27 89 views
0

嗨我正在嘗試對一系列子查詢進行分組,但不斷爲每行獲得相同的結果。如何在MySQL中對多個子查詢進行分組

 SELECT Campaign_Name, 
        (SELECT COUNT(Bounce) 
        FROM `temp_Data`) AS Sent, (SELECT COUNT(Bounce) 
              FROM `temp_Data` 
              WHERE Bounce = '0') AS Delivered, (SELECT SUM(Opened) 
                 FROM `temp_Data` 
                 WHERE Opened = '1')AS Opened 
FROM temp_Data 

GROUP BY Campaign_Name 

結果是:

Campaign Name Sent Delivered Opened 
Campaign1  300 278  196 
Campaign2  300 278  196 

我的數據是0.1所以,即使我總結它仍然給了我同樣的結果。

如何獲得每個廣告系列的個人計數?

+0

更改'where子句'你不改變它。 – NEER

+0

向我們展示您的表架構如何。 – Martin

回答

0

這可以在一個單一的查詢

SELECT 
    Campaign_Name, 
    COUNT(*) AS Sent, 
    COUNT(CASE WHEN Bounce = '0' THEN 1 ELSE NULL END) AS Delivered, 
    COUNT(CASE WHEN Opened = '1' THEN 1 ELSE NULL END) AS Opened 
FROM temp_Data 
GROUP BY Campaign_Name 

做看看control functionsCOUNT

棘手的部分是COUNT不增加NULL值,所以我用它來做一個選擇性計數。

+0

謝謝,但是您的代碼返回語法錯誤:您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'THEN 1 ELSE NULL'附近使用正確的語法, COUNT(CASE Opened ='1'THEN 1 ELSE NULL)AS'at line 4 – Drake

+0

我認爲我修復了它。請立即檢查。 – evilpenguin

+0

對不起還是一樣的錯誤 – Drake

相關問題