2013-05-01 89 views
4

我需要将一组日期分类为'Cur。 YTD','Lst。年初至今“或”其他“。年初至今基于getdate()。我有一个用于测试的临时表,它有一个名为DATETIME类型的'calendar_date'列。我想出了这个逻辑,它似乎工作。我只是想知道,如果这种方法从性能角度来看是有意义的,或者如果别的东西可能会更好。当前年迄今为止,去年迄今和其他

select calendar_date, 
case when (MONTH(calendar_date) < MONTH(getdate())) 
    or (MONTH(calendar_date) = MONTH (getdate()) 
     AND DAY(calendar_date) <= DAY(getdate())) then 
case when YEAR(calendar_date) = YEAR(GETDATE()) then 'CYTD' 
when YEAR(calendar_date) = YEAR(getdate()) - 1 then 'LYTD' 
else 'Other' 
end 
else 'Other' 
end as Tim_Tag_YTD 
from #temp1 

回答

2

您的逻辑看起来不错,并且会按原样工作。

一个简化了一点的替代方案,它假定你没有未来数据。

select 
    calendar_date, 
    Tim_Tag_YTD = case DATEDIFF(YEAR, calendar_date, GETDATE()) 
       when 0 then 'CYTD' 
       when 1 then 'LYTD' 
       else 'Other' 
       end 
from #temp1; 

在你的逻辑的情况下,明确将未来的数据为“其他”,这也可以这样做:

select 
    calendar_date, 
    Tim_Tag_YTD = case when calendar_date > GETDATE() then 'Other' else 
        case DATEDIFF(YEAR, calendar_date, GETDATE()) 
        when 0 then 'CYTD' 
        when 1 then 'LYTD' 
        else 'Other' 
        end 
       end 
from #temp1; 
0

有时直观的东西执行得更快。像这样的东西可能值得一试。

set variable @FirstOfLastYear to Jan 1 of last year 
using sql server date functions 

set @FirstOfThisYear = DateAdd(year, 1, @FirstOfLastYear) 

select 'last year' period 
, whatever else you need 
from #temp1 where calendar_date >= @FirstOfLastYear 
and calendar_date < @FirstOfThisYear 
union 
select 'this year' period 
, whatever else you need 
from #temp1 where calendar_date >= @FirstOfThisYear 
and calendar_date < getDate() 
union 
select 'other' period 
, whatever else you need 
from #temp1 where calendar_date <= @FirstOfLastYear 
or calendar_date > getdate() 

除非您尝试,否则您永远不会知道。