SQL Server选择具有不同字段值的不同where条件

时间:2016-11-01 11:39:28

标签: sql sql-server select conditional where-clause

我想从我的表offer中选择一个名为type的字段的数据,我需要为每种类型应用不同的条件。

代码可能如下所示:

select * from offer where 
if type = 1 then apply condition_1,
else if type = 2 then apply condition_2 and condition_3,
else if type = 3 then apply condition_4,

那我怎么能实现呢?

2 个答案:

答案 0 :(得分:5)

select * from offer
where (type =1 and condition_1 )
or ( type = 2 and condition_2 and condition_3 ) 
or (type = 3 and condition_3 ) 

答案 1 :(得分:0)

select * from offer 
where CASE WHEN [type] = 1 then condition_1
           WHEN [type] = 2 then (condition_2 and condition_3)
           WHEN [type] = 3 then apply condition_4 END`
相关问题