如表
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 tbaENDGOCREATE TABLE tba( Field1 VARCHAR(10), Field2 VARCHAR(10))GOINSERT INTO tbaSELECT 'A', '2012-01-01' UNIONSELECT 'B', '2012-02-01' UNIONSELECT 'C', '2012-03-01' UNIONSELECT '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 Field2B 2012-02-01C 2012-03-01D 2012-04-01*/
------解决方案--------------------
- SQL code
select * from [table] where Field='a' and Field2>'2012-2-1'union allselect * from [table] where Field1='c' and Fied3 between '2012-1-1' and '2012-5-1'union allselect * from [table] where Field2>'2012-1-1'
------解决方案--------------------
- SQL code
case when 可以用在 SELECT 、WHERE 、ORDER BY 后面
------解决方案--------------------
------解决方案--------------------
- SQL code
select * from [table] where Field='a' and Field2>'2012-2-1'union allselect * from [table] where Field1='c' and Fied3 between '2012-1-1' and '2012-5-1'union allselect * from [table] where Field2>'2012-1-1' and Field!='a' and Field!='c'
------解决方案--------------------
------解决方案--------------------
http://blog.csdn.net/dba_huangzj/article/details/7684520看看我翻译的,说不定有帮助