简体   繁体   English

在SQL中创建动态日期范围

[英]Creating a dynamic date range in SQL

How can I construct a SQL statement that will always return a start date of July 1 of the previous year, and an end date of June 30 of the current year based on GETDATE()? 如何基于GETDATE()构造一个始终返回上一年的开始日期为上一年的7月1日和本年的结束日期为6月30日的SQL语句? Right now I have 现在我有

    Dateadd(yy, Datediff(yy,1,GETDATE())-1,0) AS StartDate,
DateAdd(dd,-1,Dateadd(yy, Datediff(yy,0,GETDATE()),0)) AS EndDate

which will return January 1, 2012 and December 31, 2013 respectively.. 分别返回2012年1月1日和2013年12月31日。

You could just add another DATEADD() to your current script: 您可以将另一个DATEADD()添加到当前脚本中:

SELECT DATEADD(month,6,DATEADD(yy, DATEDIFF(yy,1,GETDATE())-1,0)) AS StartDate
      ,DATEADD(month,6,DATEADD(dd,-1,DATEADD(yy, DATEDIFF(yy,0,GETDATE()),0))) AS EndDate

I've been using this CTE for dynamic fiscal year ranges based on the current date. 我一直将此CTE用于基于当前日期的动态会计年度范围。 It returns the start and end dates for the current fiscal year based on the current date. 它根据当前日期返回当前会计年度的开始日期和结束日期。

WITH FYDates AS (
 SELECT 
    CASE 
        WHEN MONTH(GETDATE()) IN (1, 2, 3, 4, 5, 6) 
        THEN CAST(CAST(YEAR(GETDATE()) - 1 AS VARCHAR) + '/07/01' AS DATE)
        ELSE CAST(CAST(YEAR(GETDATE()) AS VARCHAR) + '/07/01' AS DATE) END AS FYStartDate, 
    CASE
        WHEN MONTH(GETDATE()) IN (1, 2, 3, 4, 5, 6)
        THEN CAST(CAST(YEAR(GETDATE()) AS VARCHAR) + '/06/30' AS DATE) 
        ELSE CAST(CAST(YEAR(GETDATE()) + 1 AS VARCHAR) + '/06/30' AS DATE) END AS FYEndDate
),

You can also create this as a view to reference that when needed. 您还可以创建此视图,以在需要时引用它。

This seems like an odd request. 这似乎是一个奇怪的请求。 One way of doing it is by constructing date strings and parsing them: 一种方法是构造日期字符串并对其进行解析:

select cast(cast(year(GETDATE()) - 1 as varchar(255))+'-07-01' as DATE) as StartDate,
       cast(cast(year(GETDATE()) as varchar(255))+'-06-30' as DATE) as EndDate

This constructs the strings in the format '2013-06-30' , which will be interpreted correctly on for most SQL Server date settings. 这将以'2013-06-30'格式构造字符串,对于大多数SQL Server日期设置,将正确解释这些字符串。

I believe (recalling something Aaron Bertrand wrote) that leaving out the hyphens always works: 我相信(回想起亚伦·伯特兰(Aaron Bertrand)所写的内容),连字符始终有效:

select cast(cast(year(GETDATE()) - 1 as varchar(255))+'0701' as DATE) as StartDate,
       cast(cast(year(GETDATE()) as varchar(255))+'0630' as DATE) as EndDate

I, as a human, just much prefer having the hyphens. 作为一个人,我非常喜欢连字符。

This should work for you: 这应该为您工作:

SELECT CAST('7/1/' + CAST(DATEPART(yy, Dateadd(yy, Datediff(yy,1,GETDATE())-1,0)) as varchar) as varchar) as startdate,
CAST('6/30/' + CAST(DATEPART(yy, Dateadd(yy, Datediff(yy,0,GETDATE()),0)) as varchar) as varchar) as enddate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM