SUM忽略WHERE但不忽略GROUP BY

时间:2014-02-15 18:34:27

标签: sql join group-by sum

我有两个表,advertsadvertsitems。这些表有一个(adverts)到多个(advertsitems)关系。我正在动态构建此查询,因此我使用WHERE 1=1来更轻松地添加新条件。

我有以下查询

  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忽略WHERE GROUP BY

1 个答案:

答案 0 :(得分: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