2014-02-15 67 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