1

我有一个日期表和一个 ID、FromDate 和 ToDate 列,如下所示

ID    FromDate                  ToDate
--    --------------            --------------
1     2013-06-10 00:00:00       2013-06-30 00:00:00
2     2013-05-10 00:00:00       2013-06-10 00:00:00
3     2012-08-01 00:00:00       2012-12-31 00:00:00
4     2013-07-10 00:00:00       2013-07-30 00:00:00

我进行检查查询并使用如下所示的 [getdate] 将列作为 Result 是否处于活动、非活动或过期

Select ID, FromDate, ToDate,
       (case when convert(varchar(8),FromDate,112) <= convert(varchar(8),getdate(),112)
                  and convert(varchar(8),ToDate,112) <= convert(varchar(8),getdate(),112) then 'Expired'       
             when convert(varchar(8),FromDate,112) <= convert(varchar(8),getdate(),112)
                  and convert(varchar(8),ToDate,112) >= convert(varchar(8),getdate(),112) then 'Active'
             when convert(varchar(8),FromDate,112) >= convert(varchar(8),getdate(),112) 
                  and convert(varchar(8),ToDate,112) >= convert(varchar(8),getdate(),112) then 'Inactive' end )'Result'
from Date

它将显示正确的结果

ID    FromDate                  ToDate                 Result
--    --------------            --------------         -------- 
1     2013-06-10 00:00:00       2013-06-30 00:00:00    Active
2     2013-05-10 00:00:00       2013-06-10 00:00:00    Expired
3     2012-08-01 00:00:00       2012-12-31 00:00:00    Expired
4     2013-07-10 00:00:00       2013-07-30 00:00:00    Inactive

但是我的Case查询太长了,有没有办法缩短代码或者提高性能呢?

4

3 回答 3

2

查询如何:

Select 
    ID, 
    FromDate, 
    ToDate,
    (case when convert(varchar(8),ToDate,112) <= convert(varchar(8),getdate(),112) then 'Expired'       
        when convert(varchar(8),getdate(),112) between convert(varchar(8),FromDate,112) and convert(varchar(8),ToDate,112) then 'Active'
        when convert(varchar(8),FromDate,112) >= convert(varchar(8),getdate(),112) then 'Inactive' end )'Result'
from Date

给定 ToDate 大于 FromDate。

于 2013-06-27T09:36:06.010 回答
0
SELECT ID, FromDate, ToDate,
    CASE WHEN ToDateStr <= NowStr THEN 'Expired'
         WHEN NowStr BETWEEN FromDateStr AND ToDateStr THEN 'Active'
         ELSE 'Inactive' END AS Result
FROM (
SELECT 
    ID, FromDate, ToDate, 
    CONVERT(varchar(8),FromDate,112) AS FromDateStr,
    CONVERT(varchar(8),ToDate,112) AS ToDateStr,
    CONVERT(varchar(8),getdate(),112) AS NowStr
FROM Date) A

鉴于 From 日期总是低于或等于 To Date

于 2013-06-27T09:47:28.507 回答
0
select id, fromDate, toDate,
case 
    when daysFromStart > 0 AND daysToEnd > 0 then 'Active'
    when daysFromStart > 0 AND daysToEnd < 0 then 'Expired'
    when daysFromStart < 0 AND daysToEnd > 0 then 'Inactive'
end
from  
(
select 
    id, fromDate, toDate, 
    DATEDIFF(day, fromDate, getdate()) as daysFromStart, 
    DATEDIFF(day, getdate(), toDate) as daysToEnd 
from orders
) t

SQL小提琴

于 2013-06-27T10:08:40.940 回答