我有一个数据库,其中包含两个我关心的日期。
StartDate + EndDate
这些日期以以下格式存储:
2008-06-23 00:00:00.000
我需要添加一段动态SQL,以便只返回当前财政年度的日期。
因此,例如01/04/2011 - 31/03/2012将是本财政年度。
因此,结束日期在这些日期内或为NULL的任何记录都被归类为‘活动’
年份部分需要是动态的,这样一旦达到2012年4月1日,我们就进入新的财政年度,并将从01/04/2012 - 31/03/13返回数据,依此类推。
我可以建议一些代码或指出我忽略的任何规则吗?
发布于 2012-01-30 22:55:44
尝试:
...
where StartDate >=
case
when month(getdate()) > 3
then convert(datetime, cast(year(getdate()) as varchar) + '-4-1')
else
convert(datetime, cast(year(getdate()) - 1 as varchar) + '-4-1')
end
and (EndDate is null or EndDate <
case
when month(getdate()) > 3
then convert(datetime, cast(year(getdate()) + 1 as varchar) + '-4-1')
else
convert(datetime, cast(year(getdate()) as varchar) + '-4-1')
end)
发布于 2012-02-23 23:48:41
开始吧:)
动态解决方案,
DECLARE @MyDate DATETIME
SET @MyDate = getDate()
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = DATEADD(dd,0, DATEDIFF(dd,0, DATEADD( mm, -(((12 + DATEPART(m, @MyDate)) - 4)%12), @MyDate ) - datePart(d,DATEADD( mm, -(((12 + DATEPART(m, @MyDate)) - 4)%12),@MyDate ))+1 ) )
SET @EndDate = DATEADD(ss,-1,DATEADD(mm,12,@StartDate ))
SELECT @StartDate,@EndDate
发布于 2012-01-30 23:29:54
创建包含字段financial_year_start
和financial_year_end
的Finacial_Year
查找表。
用未来50年的数据填充它(使用电子表格计算日期很容易)。
使用enddate
将表连接到查找表
SELECT ...
FROM Your_Table LEFT JOIN Financial_Year
ON Your_Table.enddate BETWEEN Financial_Year.financial_year_start
AND Financial_Year.financial_year_end
WHERE Your_Table.enddate IS NULL -- Active
OR (getdate() BETWEEN Financial_Year.financial_year_start
AND Financial_Year.financial_year_end)
当当前日期在接下来的两个日期之间时,当前财务将自动更改。
顺便说一句,英国的财政年度是从06-04-YYYY到05-04-YYYY,而不是1号到31号。
https://stackoverflow.com/questions/9065501
复制相似问题