tags:

views:

41

answers:

4

Hi,

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 repeatative when doing this for more then 10 FY year?

A: 

I don't have a SQL server reference handy, but here's how I'd do it in MySQL:

select date_format (date_add(mydate, interval 92 days), 'FY%Y') as FY, site, count(*)
 from mytable
 group by FY, site;

There are 92 days in October, November, and December, so I've offset by that much.

wallyk
+1  A: 

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
Stefan Mai
A: 

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
CesarGon
A: 

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
bobs