MIcrosoft SQL Server WHERE / CASE子句

时间:2014-01-17 19:48:54

标签: sql sql-server case where

我有一个where语句,它取决于一个id,并根据id确定下一个确定的位置。 EX:如果ID = 1,则如果ID<>,则where语句应该是< = 3并且b在4和7之间。 1 where语句应为< = 4且b介于5和7之间。不确定如何执行此操作。尝试了Case条款,但没有运气。

3 个答案:

答案 0 :(得分:2)

以下是带有数据的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;

enter image description here

答案 1 :(得分:1)

类似的东西:

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

答案 2 :(得分:0)

根据您的要求,您只需要使用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)