【问题标题】:SQL query | return null rows if data is not available for the columnSQL查询 |如果该列的数据不可用,则返回空行
【发布时间】:2016-05-01 04:13:35
【问题描述】:

表结构

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

问题

  1. 如果位置为 70,子位置为 115。查询应返回 id = 1
  2. 如果子位置不等于 115(任何其他子位置),查询应返回 ids 2 和 3。
  3. 子位置将作为参数出现,如果存在则返回那些特定的行,否则只有子位置中包含 null 的行

我正在使用以下查询

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

如果位置为 70 且子位置为 115,则返回 id =1。对于子位置的其他值 查询将不返回任何不应该出现的行。如果查询中传入的子位置不存在,则查询应返回与子位置为空的位置匹配的所有行

【问题讨论】:

  • 那么你的问题是什么你想检索什么
  • @Sathish 解释了现有查询的问题。

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


【解决方案1】:

我想你想要这样的东西:

       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
【解决方案2】:

您可以使用 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”和“=”

【讨论】:

    【解决方案3】:

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

    首先,给定的查询与描述的不同。通过仅获取 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 标准)以确保。

    【讨论】:

      猜你喜欢
      • 2012-12-19
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      相关资源
      最近更新 更多