【问题标题】:MIcrosoft SQL Server WHERE/ CASE clauses微软 SQL Server WHERE/ CASE 子句
【发布时间】:2014-01-17 19:48:54
【问题描述】:

我有一个依赖于 id 的 where 语句,并根据 id 确定下一个 where 。 EX:如果 ID = 1 则 where 语句应为 a 1 则 where 语句应为 aCase 子句,但没有成功。

【问题讨论】:

  • 请向我们展示您的代码!
  • 您可以使用ORWHERE (a.ID = 1 AND a<= 3 AND b >=4 and b<=7) OR (a.id <>1 AND a <= 4 AND b >=5 and b<=7) 应该适合您。

标签: sql sql-server case where


【解决方案1】:

这是 tempdb 中包含数据的示例表。

-- Just a test
use tempdb;
go

-- Drop table
if object_id('test') > 0
drop table test
go

-- Create table
create table test
(
    id int,
    a int,
    b int
);

-- Add data
insert into test values
(1, 3, 4),
(2, 4, 5),
(1, 4, 4),
(2, 5, 5),
(1, 3, 3),
(2, 4, 4);

-- Full table
select * from test;

这是使用 CASE 语句的解决方案。

-- Show the data
select 
    * 
from 
    test
where
  (
    case
        when id = 1 and a <= 3 and b between 4 and 7 then 1
        when id <> 1 and a <= 4 and b between 5 and 7 then 1
        else 0
    end
  ) = 1;

【讨论】:

  • 我很高兴能提供帮助,我的荣幸。
【解决方案2】:

类似:

where
  (id = 1 and a <= 3 and b between 4 and 7) or 
  (id <> 1 and a <= 4 and b between 5 and 7)

【讨论】:

    【解决方案3】:

    根据您的要求,您只需将 WHERE 语句与 OR 括起来即可:

    ...
    WHERE (ID = 1 AND a <= 3 AND b BETWEEN 4 AND 7)
           OR (ID <> 1 AND a<= 4 AND b BETWEEN 5 AND 7)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多