日期:2014-05-18  浏览次数:20520 次

有没有可能把Case when 语句当作where的条件表达式?
如表
  Field1 Field2
  A '2012-1-1'
  B '2012-2-1'
  C '2012-3-1'
  D '2012-4-1'
想要的结果是
select * from [table] where case when Field='a' then Field2>'2012-2-1' when Field1='c' then Fied3 between '2012-1-1' and '2012-5-1' else Field2>'2012-1-1' end
返回  
  B '2012-2-1'
  C '2012-3-1'
  D '2012-4-1'

或者有变通的办法也行

------解决方案--------------------
SQL code
where 
(Field='a' and Field2>'2012-2-1')
or
(Field1='c' and Fied3 between '2012-1-1' and '2012-5-1')
or
(Field2>'2012-1-1')

------解决方案--------------------
SQL code

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')
BEGIN
    DROP TABLE tba
END
GO
CREATE TABLE tba
(
    Field1 VARCHAR(10),
    Field2 VARCHAR(10)
)
GO
INSERT INTO tba
SELECT 'A', '2012-01-01' UNION
SELECT   'B', '2012-02-01' UNION
SELECT   'C', '2012-03-01' UNION
SELECT   'D', '2012-04-01'
GO
            
            
select * from tba 
where Field2 BETWEEN CASE when Field1 ='A' then '2012-02-01' 
                     else '2012-01-01' end  AND CASE WHEN Field1 = 'C' THEN '2012-05-01'
                                                   ELSE Field2 END
/*
Field1    Field2
B    2012-02-01
C    2012-03-01
D    2012-04-01
*/

------解决方案--------------------
SQL code
select * from [table] where Field='a' and Field2>'2012-2-1'
union all
select * from [table] where Field1='c' and Fied3 between '2012-1-1' and '2012-5-1'
union all
select * from [table] where Field2>'2012-1-1'

------解决方案--------------------
SQL code
case when  可以用在 SELECT 、WHERE  、ORDER BY  后面

------解决方案--------------------
探讨
2和4楼的代码是能解决问题,我想提高的是速度和较少的代码,如果有10个字段,每种字段又有2种情况,那用or连接效率太低,用union可是要写2^10的sql语句了

------解决方案--------------------
SQL code

select * from [table] where Field='a' and Field2>'2012-2-1'
union all
select * from [table] where Field1='c' and Fied3 between '2012-1-1' and '2012-5-1'
union all
select * from [table] where Field2>'2012-1-1' and Field!='a' and Field!='c'

------解决方案--------------------
探讨

2和4楼的代码是能解决问题,我想提高的是速度和较少的代码,如果有10个字段,每种字段又有2种情况,那用or连接效率太低,用union可是要写2^10的sql语句了

------解决方案--------------------
http://blog.csdn.net/dba_huangzj/article/details/7684520看看我翻译的,说不定有帮助