Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to calculate the first day of the current Financial Year?

What's the most efficient way to calculate the first day of the current (Australian) Financial Year?

The Australian FY begins on 01-July.

E.g.

SELECT dbo.FinancialYearStart('30-Jun-2011') returns 01-Jul-2010.

SELECT dbo.FinancialYearStart('01-Jul-2011') returns 01-Jul-2011.

SELECT dbo.FinancialYearStart('02-Jul-2011') returns 01-Jul-2011.

like image 277
Merenzo Avatar asked Jul 19 '11 08:07

Merenzo


2 Answers

One DATEADD, one DATEDIFF, and a division:

SELECT DATEADD(year,DATEDIFF(month,'19010701','20110630')/12,'19010701')

Basically, you count the number of months since some arbitrary financial year's start date (I've picked 1901), divide that number by 12 (ignoring the remainder), and add that many years back to the same arbitrary year's start date.

like image 167
Damien_The_Unbeliever Avatar answered Oct 05 '22 11:10

Damien_The_Unbeliever


I don't know if this is the most efficient, but it's fast at least...

create function dbo.FinancialYearStart
(
   @CurrentDate datetime
)
returns datetime
as
begin
   declare @CurrentYear int
          ,@FYDateThisYear datetime
          ,@FYDatePrevYear datetime

   set @CurrentYear = datepart(year, @CurrentDate)
   set @FYDateThisYear = '01-Jul-' + cast(@CurrentYear as varchar(4))
   set @FYDatePrevYear = '01-Jul-' + cast(@CurrentYear-1 as varchar(4))

   if @CurrentDate < @FYDateThisYear
   begin
      return @FYDatePrevYear
   end

   return @FYDateThisYear
end
like image 36
Andreas Ågren Avatar answered Oct 05 '22 12:10

Andreas Ågren