2013-05-01 166 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() 

除非您嘗試,否則您永遠不會知道。