CASE语句SQL日期之间

时间:2015-07-09 17:59:00

标签: sql sql-server case

我正在尝试在SQL Server中为报表参数设计CASE语句。 该报告显示了设定日期的时间范围。 expdate。

参数以字符串格式发送:

'All', '30', '31', '61', '91', '121', '150', '181+'

尝试开发一个将返回的CASE语句:

WHERE expdate 
   CASE WHEN Timeframe = 'All' Then expdate  --All Dates
   CASE WHEN timeframe=30 THEN expdate between 0 and 30 --using datediff from today
   CASE WHEN timeframe=31 THEN expdate between 31 and 60 --using datediff 
   CASE WHEN timeframe=61 THEN expdate between 61 and 90 --using datediff 

...

如果有更好的方法来执行此操作而不是CASE条款中的WHERE语句,我很满意,但这就是我过去的做法。

由于

2 个答案:

答案 0 :(得分:4)

我会使用(AND)OR(AND)结构,如下所示:

WHERE (timeframe='All')
OR (timeframe='30' AND expdate between 0 and 30)
OR (timeframe='31' AND expdate between 31 and 60)
OR (...

答案 1 :(得分:1)

使用make条件时,OR和AND不使用大小写。 我假设expdate应该存储一天。喜欢这个

WHERE (Timeframe = 'All' AND expdate=expdate)  --All Dates
OR( timeframe=30 AND expdate between 0 and 30 )--using datediff from today
OR( timeframe=31 AND expdate between 31 and 60 )--using datediff 
OR (timeframe=61 AND expdate between 61 and 90) --using datediff 
相关问题