0

如何获得一年中的财政日,即,如果我将 4 月 2 日传递给函数,它应该返回 2。财政年度从每年的 4 月 1 日开始。

4

2 回答 2

2

会计日历是特定于组织的,虽然很少见,但可以更改。最简单的解决方案是创建一个列出会计日历的表格。因此,您可以使用 CTE 进行模拟,但最好将其存储为表格。

With FiscalCalendarStarts As
    (
    Select 1 As FiscalPeriod
        , Cast('20120401' As DateTime) As StartDate
    Union All
    Select FiscalPeriod + 1
        , Case 
            When Month(StartDate) = 12 Then DateAdd(m, Month(StartDate) - 12 + 1, StartDate)
            Else DateAdd(m, 1, StartDate)
            End
    From FiscalCalendarStarts 
    Where FiscalPeriod < 12
    )
    , FiscalCalendar As
    (
    Select FiscalPeriod
        , StartDate
        , DateAdd(d, -1, DateAdd(m, 1, StartDate)) As EndDate
    From FiscalCalendarStarts
    )
Select *
From FiscalCalendar
Where @SomeDate Between StartDate And EndDate

编辑

要获得天数(我承认我没有在上述解决方案中提供),诀窍是根据输入日期确定实际的会计年度开始日期。为此,您可以执行以下操作,根据您的要求,我已将其放入一个函数中

Create Function dbo.FiscalDay ( @Input datetime )
Returns int
As

Begin 

Declare @StartDayMonth char(4);
Set @StartDayMonth = '0401';

Return  (
        Select DateDiff(d, FYStartDate, @Input) + 1
        From    (
                Select DateAdd(yyyy
                        , Case
                            When DatePart(dy, @Input) >= DatePart(dy, StartDate) Then 0
                            Else -1
                            End
                        , StartDate) As FYStartDate
                From    (
                        Select Cast( Cast(Year(@Input) As char(4)) 
                            + @StartDayMonth As datetime ) As StartDate
                        ) As S1
                ) As S
        )

End

0401我从代表财政年度开始的月份和日期的存根开始。为此,我将过去日期的年份放在前面,这样我就会得到类似201204012012 年的日期已经过去的信息。如果@Input晚于 4 月 1 日,那么我们处于@Input. 如果@Input早于 4 月 1 日,那么我们处于上一年 4 月 1 日开始的财政年度。现在我们有了财政开始日期,我们可以简单地找到它们之间的天数并加 1(否则 1-Apr 将被视为第 0 天而不是第 1 天)。请注意,通过 2012 年 3 月 31 日返回 366 而不是 365,因为 2012 年是闰年。

于 2012-05-03T06:43:26.593 回答
1

@Olivarsham,每个国家的财政年度并不常见。有些地方是 4 月至 3 月,有些地方是 1 月至 12 月。所以这是您的特殊应用要求,然后您需要为自己编写。我认为没有标准的查询。

请尝试此功能。这将返回您的会计年度的天数。

CREATE FUNCTION [dbo].[FiscalDay] (@CurrentDATE datetime)
RETURNS int

AS
BEGIN
     DECLARE @FiscalDay int;
     DECLARE @YearStartDate DateTime;
     Set @YearStartDate=Cast('20120401' As DateTime) 
     set @FiscalDay =  DATEDIFF(DAY,@YearStartDate , @CurrentDATE) 
     RETURN(@FiscalDay);
END;

GO
于 2012-05-03T06:44:44.550 回答