给出以下简化表:
--- Incident ---
ID | ID_NUMBER | AREA
--- Vehicle ---
ID | NAME | INCIDENT_ID
[仅当与事件相关的车辆没有类似M<any number><any number>
或D<any number>
的名称时,我才能计算按区域分组的事件数?
我有类似的东西,但数字似乎很大:
select count(i.ID_NUMBER), i.AREA
from Incident i
inner join Vehicle v on v.INCIDENT_ID = i.ID
where v.NAME not like 'M[0-9][0-9]'
and v.NAME not like 'D[0-9]
group by i.AREA
我认为这个数字太大,因为它要计算每个事件的每辆车,但是我只想计算没有涉及特定“ Vehicle.NAME”的Incident.ID
的数量。
为了扩展示例,给出以下内容:
---Incident---
1 | 1234 | Here
2 | 9876 | There
3 | 4567 | Here
---Vehicle---
1 | R09 | 1234
2 | F99 | 1234
3 | Q23 | 4567
4 | Y78 | 9876
5 | M42 | 9876
结果将是
2 |在这里
您应该计算不同的事件,并使用WHERE
子句代替HAVING
子句:
select count(distinct i.ID_NUMBER), i.AREA
from Incident i
inner join Vehicle v on v.INCIDENT_ID = i.ID
group by i.AREA
having sum(case when v.NAME like 'M[0-9][0-9]' or v.NAME like 'D[0-9]' then 1 else 0 end) = 0