calculate fiscal year in sql select statement?

后端 未结 10 1320
谎友^
谎友^ 2020-12-19 05:10

I have a date field that needs to return in fiscal year format. example

Start_Date        Year 
04/01/2012 -      2013
01/01/2012 -      2012
09/15/2013 -            


        
相关标签:
10条回答
  • 2020-12-19 06:10

    I just chose to do it this way. It's easy and you can replace the 09,30 with whatever you want your fiscal year end to be. Not sure if this works in anything but SQL Server though.

    CASE 
        WHEN CAST(GETDATE() AS DATE) > 
             SMALLDATETIMEFROMPARTS(DATEPART(YEAR,GETDATE()),09,30,00,000) 
        THEN 
            DATEPART(YEAR,GETDATE()) + 1 ELSE DATEPART(YEAR,GETDATE()) 
        END AS FY
    
    0 讨论(0)
  • 2020-12-19 06:12

    David has a very good solution. A simpler expression is:

    select year(dateadd(month, -3, start_date)) as FiscalYear
    

    That is, subtract 3 months and take the year.

    EDIT:

    As noted in the comment, this seems to produce one year too early. Here are two solutions:

    select year(dateadd(month, 9, start_date)) as FiscalYear
    
    select 1 + year(dateadd(month, -3, start_date)) as FiscalYear
    
    0 讨论(0)
  • 2020-12-19 06:12
    SELECT CASE WHEN DatePart(Month, Start_Date) >= 4
                THEN DatePart(Year, Start_Date) + 1
                ELSE DatePart(Year, Start_Date)
           END AS Fiscal_Year
    FROM data
    
    0 讨论(0)
  • 2020-12-19 06:17
    DECLARE @STARTDATE DATETIME, @ENDDATE DATETIME,@CURR_DATE DATETIME
    SET @CURR_DATE='2015-01-30'
    IF MONTH(@CURR_DATE) IN (1,2,3)
    BEGIN
        SET @STARTDATE= CAST( CAST(YEAR(@CURR_DATE)-1 AS VARCHAR)+'/04/01'  AS DATE)
        SET @ENDDATE= CAST( CAST(YEAR(@CURR_DATE)  AS VARCHAR)+'/03/31'  AS DATE)
    END
    ELSE
    BEGIN
        SET @STARTDATE= CAST( CAST(YEAR(@CURR_DATE) AS VARCHAR)+'/04/01'  AS DATE)
        SET @ENDDATE= CAST( CAST(YEAR(@CURR_DATE)+1 AS VARCHAR)+'/03/31'  AS DATE)
    END
    SELECT @STARTDATE AS ST_FI,@ENDDATE AS END_FY
    
    0 讨论(0)
提交回复
热议问题