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?
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
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
Yes, it is a bit repetitive. I'd be using DatePart and some easy to discern rules:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With