2010-10-09 197 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