【问题标题】:SQL where "something" plus "this" or "that"SQL where "something" 加上 "this" 或 "that"
【发布时间】:2018-08-01 04:51:14
【问题描述】:

我需要创建一个选择“某事”的查询,然后从列表中选择其他内容。例如,选择一辆救护车,然后从列表中选择一辆或多辆。

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

以上是我目前所拥有的,它有些作用,但不能保证我有救护车,这是必须的。成功的查询结果包括:

救护车和医务人员、救护车和护理人员塔、救护车和护理人员救援引擎、救护车和......

【问题讨论】:

  • 您应该看到救护车记录以及所有其他记录。也许存在空格问题,或者您使用的是 TOP 5 或类似的东西?
  • 这是sql server。
  • 如果救护车与其他车辆位于不同的列(不是 unit_type),这将更有意义
  • 这些值仅来自一张表。
  • 请提供您的表格的示例数据及其预期结果。

标签: sql sql-server


【解决方案1】:

我想你只是想要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;

【讨论】:

  • 使用IN 肯定更干净,但您的结果集将与 OP 相同。
  • @KenshinH 那么为什么不编辑您的问题并向我们展示一些示例数据以及您期望的结果
【解决方案2】:

一个临时解决方案,我使用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

有两个 where 条件,你肯定会使用你需要的一个 此查询将告诉您哪些 unit_types 不可用,哪些可用。

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多