我需要创建一个选择"的东西"然后从列表中选择其他内容。例如,选择一辆救护车,然后从列表中选择一个或多个。
select r.unit_type
from dw_prod.dbo.vw_unit_response r
where CallTypeGrp2 = 'als'
and
(
r.unit_type='Ambulance'
or r.unit_type = 'Medic'
or r.unit_type = 'Paramedic Engine'
or r.unit_type = 'Paramedic Truck'
or r.unit_type = 'Paramedic Tower'
or r.unit_type = 'Paramedic Rescue Engine'
or r.unit_type = 'Paramedic Brush Engine'
or r.unit_type = 'Paramedic Rescue Squad'
)
group by r.CADIncidentNumber
, r.unit_type
order by r.CADIncidentNumber
以上是我到目前为止所做的一些事情,但它并不能保证我的救护车,这是必须的。成功的查询结果包括:
救护车& Medic,Ambulance&护理人员塔,救护车&护理人员救护引擎,救护车& ...
答案 0 :(得分:0)
我想你只想要in
:
where r.unit_type in ('Ambulance', 'Medic', 'Paramedic Engine', 'Paramedic Truck', 'Paramedic Tower',
'Paramedic Rescue Engine', 'Paramedic Brush Engine', 'Paramedic Rescue Squad'
)
作为一个额外的好处,一些数据库在列表中的优化要比一系列or
比较好得多。
编辑:
现在问题更清楚了,只需使用HAVING
子句:
select r.CADIncidentNumber, r.unit_type
from dw_prod.dbo.vw_unit_response r
where CallTypeGrp2 = 'als' and
r.unit_type in ('Ambulance', 'Medic', 'Paramedic Engine', 'Paramedic Truck', 'Paramedic Tower',
'Paramedic Rescue Engine', 'Paramedic Brush Engine', 'Paramedic Rescue Squad'
)
group by r.CADIncidentNumber, r.unit_type
having sum(case when r.unit_type = 'Ambulance' then 1 else 0 end) > 0
order by r.CADIncidentNumber;
答案 1 :(得分:0)
我使用unions
的临时解决方案,但您可以创建临时表或其他方式来获取表。
;with cte as (
select 'Ambulance' as unit_type union
select 'Medic' as unit_type union
select 'Paramedic Engine' as unit_type union
select 'Paramedic Truck' as unit_type
)
select *
from cte a
left join [dbo].[OriginalTable] b on b.typeName = a.unit_type
where b.Id is null -- for those which are not found
where b.Id is not null -- only found
有两个条件,你绝对会使用你需要的条件 此查询将告诉您哪些unit_types不可用以及哪些可用。