SQL查询|如果数据不适用于列,则返回空行

时间:2014-09-25 03:56:47

标签: sql sql-server sql-server-2008

表格结构

|id |location|sub-location|
--------------------------
|1| 70  |115|
|2| 70  |NULL|
|3| 70  |NULL|

问题

  1. 如果location为70且sub-location为115. Query应返回id = 1
  2. 如果子位置不等于115(任何其他子位置),则查询应返回ID 2和3。
  3. 子位置将作为参数出现,如果存在则返回那些特定行,否则只返回子位置中包含null的行
  4. 我正在使用以下查询

    Select id, location, sub-location
    From table1 Where location = @location and (sub-location is null or sub-location = @sub-location)
    

    如果位置为70且子位置为115,则返回id = 1.对于其他子位置值 query将不返回任何不应该是这种情况的行。如果在查询中传递的子位置不存在,则查询应返回与子位置为空的位置匹配的所有行

3 个答案:

答案 0 :(得分:2)

我想你想要这样的东西:

       declare @sublocation int,
                        @location int
                   set @location = 70 
                   set @sublocation = 115

                select id
                from MyTable a
                where a.location = @location
                and ( a.sublocation  = @sublocation
                      or (a.sublocation is null and 
                        not exits (select 1 
                        from Mytable sub 
                        where sub.sublocation = @sublocation)
                    ) )

答案 1 :(得分:1)

您可以使用CTE:

SQL Fiddle

    declare @sublocation int
    declare @location int

    set @location = 70

    set @sublocation=116

    ;with cte(id, location, sublocation)
    as
    (
    select id, location, coalesce(sublocation, -9999) as sublocation
    from table1
    where location=@location
    )

    select id, location, case when sublocation=-9999 then null else sublocation end from cte
    where
    sublocation =
      case when exists(select * from table1 where sublocation=@sublocation) then
          @sublocation
      else -9999
      end

这里的想法,如果不存在子位置,则将其转换为-9999或一些不合逻辑的整数。然后用它进行比较。原因是,我们无法在使用case语句的一个where子句中比较“is null”和“=”

答案 2 :(得分:0)

尽管这个请求已经很老了,但我想我仍然可以回答: - )

首先,给定的查询与所描述的不同。通过仅获取NULL条目,它适用于未找到的子位置(即,与示例中的115不同)。但是对于匹配的子位置(即示例中的115),它获得匹配记录和NULL记录,这是不希望的。

并且很容易减少后一种情况的结果,只选择匹配的条目。

select top(1) with ties 
  id, location, sub_location
from table1 
where location = @location and (sub_location is null or sub_location = @sub_location)
order by case when sub_location is null then 2 else 1 end;

所以我们所做的就是按子位置是否为空来排序。然后我们只保留顶部组,即匹配的条目(如果有的话),或者是NULL条目。

顺便说一句:sub-location的查询真的有效吗?它看起来像是两列(sublocation)的减法。这在SQL Server中有用吗?好吧,我已经用sub_location(符合SQL标准)替换了列名,以确保。

相关问题