Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Fiscal year using SQL Server

Tags:

sql

sql-server

Is there a way in SQL Server that can show the Fiscal Year (begins on October 1 and ends on September 30) from a table which has a date column (1998 to 2010). Here is what I have done:

select 'FY1999' as FY, site, count(*)
from mytable
where mydate >='10/1/1998' 
    and mydate <'10/1/1999'
group by site

select 'FY2000' as FY, site, count(*)
from mytable
where mydate >='10/1/1999' 
    and mydate <'10/1/2000'
group by site

select 'FY2001' as FY, site, count(*)
from mytable
where mydate >='10/1/2000' 
    and mydate <'10/1/2001'
group by site

Isn't it too much repetitive when doing this for more then 10 FY year?

like image 352
Tom Avatar asked Oct 09 '10 17:10

Tom


3 Answers

Here's a single query that will give you the information you want.

SELECT DATEPART(yyyy, DATEADD(mm, 3, mydate)) AS FY, site, COUNT(*) AS row_count
FROM mytable
GROUP BY DATEPART(yyyy, DATEADD(mm, 3, mydate)), site
like image 124
bobs Avatar answered Oct 12 '22 18:10

bobs


You can even create your user-defined function in SQL Server that takes a date argument and returns the fiscal year as an int:

CREATE FUNCTION GetFiscalYear(@TheDate date)
RETURNS int
AS
BEGIN
    DECLARE @FiscalYear int  

    IF DATEPART(month, @TheDate) < 10
        SELECT @FiscalYear = DATEPART(year, @TheDate)
    ELSE
        SELECT @FiscalYear = DATEPART(year, @TheDate) + 1  

    RETURN @FiscalYear
END

Then you can use this as, for example:

SELECT Id, ShippingDate, GetFiscalYear(ShippingDate)
FROM SomeTable
like image 38
CesarGon Avatar answered Oct 12 '22 20:10

CesarGon


Yes, it is a bit repetitive. I'd be using DatePart and some easy to discern rules:

  • Fiscal year is the year of the date if the month is < 10.
  • Fiscal year is the year of the date + 1 if the month >= 10
like image 1
Stefan Mai Avatar answered Oct 12 '22 19:10

Stefan Mai