How would you calculate the fiscal year from a date field in a view in SQL Server?
Start of fiscal year:
DATEADD(MONTH, DATEDIFF(MONTH, '20100401', getdate()) / 12 * 12, '20100401')
End of Fiscal Year:
DATEADD(MONTH, DATEDIFF(MONTH, '20100401', getdate()) / 12 * 12, '20110331')
Replace getdate()
with your own date if required
Building on the answer above by @csaba-toth, and assuming your fiscal year starts on the first day of the month
year(dateadd(month, (12 -
FyStartMonth + 1), <date>)
My FY starts 1-July, the 7th month, so my constant is (12 - 7 + 1 =) 6.
Test cases (as of 25-Sep-2019):
select year(dateadd(month, 6, getdate()))
, year(dateadd(month,6, '1/1/2020'))
, year(dateadd(month, 6, '7/1/2020'))
, year(dateadd(month, 6, '6/30/2020'))
Returns:
2020 2020 2021 2020
I do believe this is the simplest and perhaps most comprehensible implementation.
Here is Australian Financial year start date code
select DATEADD(dd,0, DATEDIFF(dd,0, DATEADD( mm,
-(((12 + DATEPART(m, getDate())) - 7)%12), getDate() )
- datePart(d,DATEADD( mm, -(((12 + DATEPART(m, getDate())) - 7)%12),getDate() ))+1 ) )
It returns like '2012-07-01 00:00:00.000'
DECLARE @DateFieldName DATETIME = '1/1/2020'
--UK Fiscal Year
SELECT
CASE
WHEN MONTH(@DateFieldName) in (1,2,3)
THEN CONCAT(YEAR(@DateFieldName) -1 , '-' , YEAR(@DateFieldName) )
ELSE CONCAT(YEAR(@DateFieldName) , '-' , YEAR(@DateFieldName)+1 )
END AS [FISCAL YEAR]
--RESULT = '2019-2020'
More simple for Australians :)
(YEAR(DATEADD(Month,-((DATEPART(Month,[Date])+5) %12),[Date]))+) AS Financial_Year
Given @FiscalYearStartMonth
is your fiscal year start month (numeric)
and @Date
is the date in question, do the following:
SELECT
CASE
WHEN @FiscalYearStartMonth = 1 OR @FiscalYearStartMonth > MONTH(@Date)
THEN YEAR(@Date)
ELSE YEAR(@Date) + 1
END AS FiscalYear
You can abstact this away in a function, or use as a column in a derived view