Sql 本年度迄今、上一年度迄今和其他
我需要将一组日期分类为“Cur”或“Cur”。年初至今。“年初至今”或“其他”。YTD基于getdate。我有一个用于测试的临时表,它有一个名为“calendar\u date”的DATETIME类型的列。我想出了这个逻辑,它似乎起了作用。我只是想知道,从性能角度来看,这种方法是否有意义,或者其他方法是否更好Sql 本年度迄今、上一年度迄今和其他,sql,sql-server-2008,Sql,Sql Server 2008,我需要将一组日期分类为“Cur”或“Cur”。年初至今。“年初至今”或“其他”。YTD基于getdate。我有一个用于测试的临时表,它有一个名为“calendar\u date”的DATETIME类型的列。我想出了这个逻辑,它似乎起了作用。我只是想知道,从性能角度来看,这种方法是否有意义,或者其他方法是否更好 select calendar_date, case when (MONTH(calendar_date) < MONTH(getdate())) or (MONTH(ca
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
你的逻辑看起来很好,可以按原样工作 一个稍微简化的替代方案,假设您没有未来的数据 在您的逻辑中,您明确地将未来数据放入“其他”中,您也可以这样做:
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;
有时一些不直观的东西执行得更快。像这样的东西可能值得一试
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()
除非你尝试,否则你永远不会知道
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()