2010-10-09 245 views
1

SQL Server中有沒有一種方法可以從具有日期列(1998到2010)的表中顯示會計年度(從10月1日開始到9月30日結束)。以下是我所做的:SQL Server 2008問題

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 

這樣做不是太多的重複,當這樣做超過10財年?

+0

你想要什麼恰好說明了什麼? – CesarGon 2010-10-09 01:21:05

+2

你的問題並不十分清楚。嘗試將你的問題看作是*不知道你腦子裏發生了什麼的人。 – 2010-10-09 01:21:34

回答

2

您可以創建一個函數來計算fical年:

CREATE FUNCTION fn_FiscalYear(@date DATETIME) 
RETURNS INT 
AS BEGIN 
    DECLARE @AddYear int 
    SET @AddYear = 0 
    IF (DATEPART(mm, @date) > 9) 
     SET @AddYear = 1 

    RETURN(DATEDIFF(yyyy, '1999-10-01', @date)[email protected]) 
END 
go 

select dbo.fn_FiscalYear('1999-10-01') 
select dbo.fn_FiscalYear('2000-09-30') 
select dbo.fn_FiscalYear(GETDATE()) 
select dbo.fn_FiscalYear('2005-01-01') 
select dbo.fn_FiscalYear('2004-12-31') 

,並使用該功能在查詢:

SELECT dbo.fn_FiscalYear(TransactionDate), Amount 
FROM dbo.Transactions 
4
select case 
      when month(MyDate) >= 10 then Year(MyDate) + 1 
      else Year(MyDate) 
     end as FiscalYear, 
    count(*) as Count 
from MyTable 
group by case 
      when month(MyDate) >= 10 then Year(MyDate) + 1 
      else Year(MyDate) 
     end 
+0

你打我吧:) +1 – 2010-10-09 02:17:18

+0

你也可以在分組/顯示+1之前的日期還有10個月 – 2010-10-09 02:57:34