2014-02-15 92 views
1

我有兩個表,advertsadvertsitems。這些表得到了一個(adverts)與很多(advertsitems)的關係。我正在動態構建此查詢,因此我使用WHERE 1=1來更容易地添加新條件。SUM忽略WHERE但不是GROUP BY

我有以下查詢

SELECT a.title AS adtitle, 
     a.id AS adid, 
     a.price, 
     a.image AS image, 
     a.description, 
     SUM(ai.quantity) as quantity, 
     a.shipping, 
     a.customs, 
     a.createdate 
    FROM adverts a 
      LEFT JOIN advertsitems ai 
        ON a.id = ai.advertid 
    WHERE 1=1 
    AND ai.country LIKE '%AF%' 
GROUP BY a.id 
ORDER BY a.id DESC 

SUM(ai.quantity)結果是2在這種情況下。如果我刪除WHERE條件ai.country LIKE,結果爲6.我想在兩個分離的列中檢索這兩個值。所以基本上我想要一個SUM忽略的WHEREGROUP BY

回答

0

使用條件彙總:

SELECT a.title AS adtitle, a.id AS adid, a.price, a.image AS image, a.description, 
     SUM(ai.quantity) as totalquantity, 
     SUM(case when ai.country LIKE '%AF%' then quantity else 0 end) as AFquantity 
     a.shipping, a.customs, a.createdate, ai.country 
FROM adverts a LEFT JOIN 
    advertsitems ai 
    ON a.id = ai.advertid 
WHERE 1=1 
GROUP BY a.id 
ORDER BY a.id DESC 

如果你真的想按國家過濾,然後用having條款。它會做過濾後聚集:

SELECT a.title AS adtitle, a.id AS adid, a.price, a.image AS image, a.description, 
     SUM(ai.quantity) as totalquantity, 
     SUM(case when ai.country LIKE '%AF%' then quantity else 0 end) as AFquantity 
     a.shipping, a.customs, a.createdate 
FROM adverts a LEFT JOIN 
    advertsitems ai 
    ON a.id = ai.advertid 
WHERE 1=1 
GROUP BY a.id 
HAVING ai.country LIKE '%AF%' 
ORDER BY a.id DESC 
+0

嘿,感謝(再次)爲您(快速)的答覆。如果我運行您的查詢,我會得到廣告上的所有結果,但我只希望廣告與'ai.country LIKE'匹配。如果我在查詢中添加'ai.country LIKE',我會得到相同的結果,而colums的totalquantity和afquantity都是2. – Dylan

+0

謝謝!你是一個天才:D我只需要將ai.country添加到SELECT中,否則我會得到'具有子句中的未知列'。 – Dylan