是否排除分组和分组?

问题描述 投票:0回答:1

给出以下简化表:

--- 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 |在这里

sql sql-server tsql ssms
1个回答
0
投票

您应该计算不同的事件,并使用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
© www.soinside.com 2019 - 2024. All rights reserved.