使用SQL Server对会计年度进行分组

前端之家收集整理的这篇文章主要介绍了使用SQL Server对会计年度进行分组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
sql Server中是否有一种方法可以从具有日期列(1998年到2010年)的表中显示会计年度(从10月1日开始到9月30日结束).这是我做的:
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,count(*)
from mytable
where mydate >='10/1/1999' 
    and mydate <'10/1/2000'
group by site
select 'FY2001' as FY,count(*)
from mytable
where mydate >='10/1/2000' 
    and mydate <'10/1/2001'
group by site

这个年度超过10年这样做是不是太重复了?

解决方法

您甚至可以在sql Server中创建用户定义的函数,该函数采用日期参数并将会计年度作为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

然后你可以使用它,例如:

SELECT Id,ShippingDate,GetFiscalYear(ShippingDate)
FROM SoMetable
原文链接:https://www.f2er.com/mssql/77911.html

猜你在找的MsSQL相关文章