在SQL中有条件地使用WHERE子句

时间:2012-07-05 06:21:54

标签: sql sql-server tsql

看看这个:

SELECT clientid,clientname,startdate,enddate,age FROM clients 
WHERE clientid IN (1,2,3,4,5)
AND CASE WHEN age>10 THEN enddate>'31-05-2013'
END

我的问题:我希望第二个条件 enddate> '31 -05-2013' 仅在年龄> 10

此查询有什么问题?

5 个答案:

答案 0 :(得分:3)

Select clientid,clientname,startdate,enddate,age from clients 
where clientid in (1,2,3,4,5)
and (age <= 10 OR enddate > '31-05-2013')

答案 1 :(得分:2)

我认为你不能使用像这样的案例表达。试试这个:

Select clientid,clientname,startdate,enddate,age from clients 
where clientid in (1,2,3,4,5)
and (age<=10 or enddate>'31-05-2013')

答案 2 :(得分:1)

有几件事可能是错的。一个是日期通常是2013-05-31顺序。这可能会根据区域设置而改变;让我们这样假设。

否则,您需要更简单地将查询编写为:

SELECT clientid, clientname, startdate, enddate, age
  FROM clients 
 WHERE clientid IN (1,2,3,4,5)
   AND ((age > 10 AND enddate > '31-05-2013') OR (age <= 10))

或者,使用案例:

SELECT clientid, clientname, startdate, enddate, age
  FROM clients 
 WHERE clientid IN (1,2,3,4,5)
   AND CASE 
       WHEN age > 10 THEN enddate > '31-05-2013'
       ELSE TRUE
       END

(无ELSE子句的默认值为NULL。)

答案 3 :(得分:0)

Select clientid,clientname,startdate,enddate,age from clients
where clientid in (1,2,3,4,5)
and  ( (age>10 and enddate>'31-05-2013') or (age<=10 and enddate<='31-05-2013') )

答案 4 :(得分:0)

我会使用明确的dateformat

Select clientid,clientname,startdate,enddate,age from clients  
where clientid in (1,2,3,4,5) 
and (age <= 10 OR enddate > '20130531') 

查看原因http://beyondrelational.com/modules/2/blogs/70/posts/10899/understanding-datetime-column-part-ii.aspx