如何使用sum获取与查询中的条件不匹配的行

时间:2012-01-18 03:47:25

标签: sql ms-access

SELECT k.condition, 
       SUM(IIf(AnimalType=3,1,0)) AS Carnivore, 
       SUM(IIf(AnimalType=4,1,0)) as Herbivore
From Animals a inner join knownconditions k on a.id = k.id
where a.id in (3, 11, 12)
AND (AnimalType=3 OR AnimalType = 4)
Group by a.id, k.id

上述查询会带来所有具有特定条件类型的动物。像这样:

Condition   | Carnivore | Herbivore
------------| ----------|-------------
Condition1  | 33        | 3
Condition2  | 2         | 4

为了这个例子,考虑knownconditions表中有一条记录,如下面

ID    | Condition
------|------------
3     | Condition3

幸运的是,Animals表中的动物没有条件Condition3。因此,我上面的查询甚至没有列出Condition3

如何修改我的查询以便带来的结果是:

Condition   | Carnivore | Herbivore
------------| ----------|-------------
Condition1  | 33        | 3
Condition2  | 2         | 4
Condition3  | 0         | 0

3 个答案:

答案 0 :(得分:0)

转换为外部联接:

SELECT k.condition,  
   SUM(IIf(AnimalType=3,1,0)) AS Carnivore,  
   SUM(IIf(AnimalType=4,1,0)) as Herbivore 
From knownconditions k 
  Left join Animals a  
      on a.id = k.id 
         And a.id in (3, 11, 12) 
         And AnimalType In (3, 4) 
Group by k.id, a.id 

这将产生knownConditions中的所有条件,并且对于每种动物类型,产生具有每种条件的已知条件中的记录总数。

答案 1 :(得分:0)

将左连接视为动物VS. knownconditions。这样动物就会根据病情进行计数。如果条件不满足则返回0.

SELECT k.condition, 
       SUM(IIf(AnimalType=3,1,0)) AS Carnivore, 
       SUM(IIf(AnimalType=4,1,0)) as Herbivore
From Animals a LEFT JOIN knownconditions k on a.id = k.id
AND a.id in (3, 11, 12)
AND (AnimalType=3 OR AnimalType = 4 ) 
Group by a.id, k.id

请评论工作。我没有测试过它。

答案 2 :(得分:0)

使用文字和联合的不同方法:

SELECT condition, SUM(Carnivore), SUM(Herbivore)
FROM
(
    SELECT k.condition, 
       SUM(IIf(AnimalType=3,1,0)) AS Carnivore, 
       SUM(IIf(AnimalType=4,1,0)) as Herbivore
    From Animals a inner join knownconditions k on a.id = k.id
    where a.id in (3, 11, 12)
    AND (AnimalType=3 OR AnimalType = 4)
    Group by k.condition, a.id, k.id
    UNION
    SELECT condition, 0, 0
    From knownconditions
)
GROUP BY condition