或者使用Group By的条件

时间:2012-11-30 19:06:48

标签: sql database ms-access

我有两张桌子,一张是观察员,另一张是动物。

我试图得到观察者的名字,他们看过5只以上的动物或看过熊。

我能够获得超过4只动物的观察者,但不知道如何进行OR声明。

这是我的代码:

SELECT o.last_name, o.first_name, a.observer_id, count (a.observer_id) as Animals_Seen
from animals as a inner join observer as o 
on a.observer_id = o.observer_id
group by a.observer_id, o.last_name, o.first_name
having count (a.observer_id) > 4;

这就是我得到的:

enter image description here

3 个答案:

答案 0 :(得分:1)

应该是WHERE子句

SELECT fields
FROM tables
WHERE COUNT(a.observer_id) > 4
OR a.observer_id = bear_id

答案 1 :(得分:1)

每当发现熊时,将布尔值设置为1 ...然后检查观察者的熊数是否> 0:

select
    o.last_name, o.first_name, a.observer_id, count(a.observer_id) as Animals_Seen,
    sum(iif(a.animal = "bear", 1, 0)) as BearCount
from 
    animals as a inner join observer as o 
on 
    a.observer_id = o.observer_id
group by 
    a.observer_id, o.last_name, o.first_name
having
    count(a.observer_id) > 4 or sum(iif(a.animal = "bear", 1, 0)) > 0

答案 2 :(得分:0)

只需将 Or 语句添加到having子句

即可
SELECT o.last_name, o.first_name, a.observer_id, count (a.observer_id) as Animals_Seen
from animals as a inner join observer as o 
on a.observer_id = o.observer_id
group by a.observer_id, o.last_name, o.first_name
having count (a.observer_id) > 4 OR a.observer_id = 'bear';