我需要在SSMS上的SQL中创建一个函数,以获得与特定日期范围相关的列的总和(从一年的9-1到下一年的8-31)。问题是,这个日期范围每年都会发生变化。
我知道如何在SQL中编码:
Create View DateRangeRDView AS
Select RD1, RD2, RD3, RD4
From SomeTable
Where PerformanceDate BETWEEN '20140901' AND '20150831'
但是当视图中的日期范围需要更改为BETWEEN '20150901' AND '20160831'
时,我必须创建一个全新的视图。
我也知道GetDate()
获取当前日期,但我不确定如何实现它以帮助这里。是否可以执行此操作,GetDate()
可以检查它是否超过09-01
而未声明年份,如果已超过09-01
SELECT between 09-01-CURRENTYEAR and 08-31-NEXTYEAR
或之前09-01
SELECT between 09-01-LASTYEAR and 08-31-CURRENTYEAR
?这将始终与此特定视图/查询中的当前年份相关
答案 0 :(得分:2)
我猜您正在使用SQL Server(基于日期格式和对getdate()
的引用:
Create View DateRangeRDView AS
Select RD1, RD2, RD3, RD4
From SomeTable
Where PerformanceDate BETWEEN cast(datepart(year, getdate()) + '0901' as date) AND
cast(datepart(year, dateadd(year, 1, getdate())) + '0831' as date)
答案 1 :(得分:2)
如果这是Sql Server,那么我认为这将有所帮助:
where PerformanceDate between
case when month(getdate())>=9
then cast(year(getdate()) as char(4)) + '0901'
else cast(year(getdate())-1 as char(4))+ '0901' end
and
case when month(getdate())>=9
then cast(year(getdate())+1 as char(4)) + '0901'
else cast(year(getdate()) as char(4))+ '0901' end