SQL 当前年份的日期范围

SQL Date Range from current year

我需要在 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 或者它在 [=15= 之前] SELECT between 09-01-LASTYEAR and 08-31-CURRENTYEAR?这将始终与本年度相关 view/query

我猜您正在使用 SQL 服务器(基于日期格式和对 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)

如果这是 Sql 服务器,那么我认为这会有所帮助:

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