计算季度开始日期

时间:2018-07-19 18:45:25

标签: sql sql-server tsql

由于我必须根据@firstMonthOfFiscalyear参数从任何财政年度开始日期计算特定季度的开始日期和季度号。假设@firstMonthOfFiscalyear = 4表示我的财政年度开始日期是4月1日,我的季度没有开始,如下所示。 第1季度-4月至6月 第2季度-7月至9月 第三季度-十月至十二月 第4季度-1月至3月

此季度号将根据@firstMonthOfFiscalyear参数值而更改。

由此我可以获取季度号,但不能获取该季度的开始日期。所以任何人都可以在这方面帮助我。

DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
DECLARE @firstMonthOfFiscalyear int = 4     --Finanical year start month
SET @StartDateTime = '2017-04-01'
SET @EndDateTime = '2019-03-31';
WITH DateRange(Dates) AS 
(
SELECT @StartDateTime as Date
Union ALL
SELECT DATEADD(d,1,Dates)
FROM DateRange 
WHERE Dates < @EndDateTime
)
SELECT Dates
,FLOOR(((12 + MONTH(Dates) - @firstMonthOfFiscalyear) % 12) / 3 ) + 1   as quarterNo
    , DATEADD(month, (IIF((month(dates)-@firstMonthOfFiscalyear)<0,(month(dates)-@firstMonthOfFiscalyear)+12,(month(dates)-@firstMonthOfFiscalyear))/3)*3,  CAST( DATEFROMPARTS(year(dates),@firstMonthOfFiscalyear ,1) as Datetime)) as QuarterStartDate
FROM DateRange
OPTION (MAXRECURSION 0)

3 个答案:

答案 0 :(得分:0)

由于可以使用DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)找到年初,因此只需添加@firstMonthOfFiscalyear - 1个月:

DATEADD(mm,@firstMonthOfFiscalyear,DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)

How to get the first and last date of the current year?

或通过构建字符串:

CAST(CAST(@firstMonthOfFiscalyear AS VARCHAR(2)) + '/1/' CAST(DATEPART(YY,GETDATE()) AS VARCHAR(4)) AS DATE)

答案 1 :(得分:0)

您可以尝试根据您的输入查询此查询,以获取接下来4个季度的开始日期。使用DATEFROMPARTS function来建立第一季度的开始日期,然后使用CTE来建立下一个季度的开始日期,方法是将上一个季度增加3个月。

    DECLARE @firstMonthOfFiscalyear int = 4
    ;WITH MyQuarters(q, qDate) as
    (
        select 1,    
         DATEFROMPARTS(year(getdate()), @firstMonthOfFiscalyear, 1) -- First quarter date
         UNION ALL
         select q+1,
         DATEADD(q, 1, qdate) -- next quarter start date
         from MyQuarters
         where q <4 -- limiting the number of next quarters
     )
    select * from MyQuarters

输出:

q   qDate
1   2018-04-01
2   2018-07-01
3   2018-10-01
4   2019-01-01

答案 2 :(得分:0)

要计算会计季度,您可以减去月份差并计算“实际”季度:

DATEPART(quarter, DATEADD(month, 1-@firstMonthOfFiscalyear, Dates))

要计算季度的开始,请为减去月份差的日期计算“实际”季度的开始,最后再次添加月份差。利用@date返回一个整数,因此被3除为整数除法的事实,DATEDIFF的“实数”四分之一的开始可以如下计算:中括号,则必须在整数除法之后进行乘法运算):

DATEADD(month, 3*(DATEDIFF(month, 0, @date)/3), 0)

Dates代替@date,减少@firstMonthOfFiscalyear-1个月,最后增加@firstMonthOfFiscalyear-1个月,这将是

DATEADD(month, @firstMonthOfFiscalyear-1, DATEADD(month, 3*(DATEDIFF(month, 0, DATEADD(month, 1-@firstMonthOfFiscalyear, Dates))/3), 0))

这可以简化为

DATEADD(month, @firstMonthOfFiscalyear-1 + 3*((DATEDIFF(month, 0, Dates)+1-@firstMonthOfFiscalyear)/3), 0)

最后,您的查询可能如下所示:

SELECT Dates
, DATEPART(quarter, DATEADD(month, 1-@firstMonthOfFiscalyear, Dates)) AS quarterNo
, DATEADD(month, @firstMonthOfFiscalyear-1 + 3*((DATEDIFF(month, 0, Dates)+1-@firstMonthOfFiscalyear)/3), 0) AS QuarterStartDate
FROM DateRange