如何根据会计年度动态获取数据

how to get data dynamically in view basing on fiscal year

如何动态创建视图以获取基于财政年度(Financial year)的数据。

让我们看看我有样本数据的样本数据。

    Declare @t table(StartDate date )
    insert into @t values('04/01/2012'),
    ('01/01/2012'),
    ('09/15/2013'),
    ('04/01/2014'),
    ('01/01/2015'),
    ('09/15/2015'),
    ('04/01/2016'),
    ('01/01/2017'),
    ('09/15/2016')

举个例子,如果我今天有 运行 个视图,我需要从 2016 年 3 月到 2017 年 4 月获取。如果我在 2017 年 5 月有 运行 个视图,我需要从 3 月获取数据2017 年至 2017 年 5 月。 我可以在 Sql 服务器脚本或存储过程中解决它,但如何在 Dynamic View 或 View 中获得相同的结果。 建议我!

我的脚本

DECLARE @STARTDATE DATETIME, @ENDDATE DATETIME,@CURR_DATE DATETIME
SET @CURR_DATE='2016-06-01'
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  * from @t
where StartDate between 
 @STARTDATE  AND @ENDDATE 
 order by year (StartDate)

它提供了我想要的财政年度 (2016-2017) 数据 但是我如何使用它并创建一个 VIEW

如果您已经在 script\stored 过程中计算出代码,您可以在 Table-Valued User-Defined Functions.

中重复使用此类代码

这样您就可以像查询视图一样查询 UDF。

您可以尝试这样的操作:

select t.* 
from @t t
cross join (
   select startdate = case 
                         when MONTH(@CURR_DATE) IN (1,2,3)
                            then CAST( CAST(YEAR(@CURR_DATE)-1 AS VARCHAR)+'/04/01'  AS DATE)
                         else CAST( CAST(YEAR(@CURR_DATE) AS VARCHAR)+'/04/01'  AS DATE)
                      end) s
cross join (
   select enddate = case 
                       when MONTH(@CURR_DATE) IN (1,2,3)
                          then CAST( CAST(YEAR(@CURR_DATE)  AS VARCHAR)+'/03/31'  AS DATE)
                       else CAST( CAST(YEAR(@CURR_DATE)+1 AS VARCHAR)+'/03/31'  AS DATE)
                    end) e
where t.StartDate between s.startdate and e.enddate
order by year (t.StartDate)

您可以在视图中使用基于当前日期 (GETDATE()) 的 cte 日期:

;WITH cte AS (
SELECT  CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE())-1 AS VARCHAR)+'/04/01'  AS DATE) ELSE CAST( CAST(YEAR(GETDATE()) AS VARCHAR)+'/04/01'  AS DATE) END AS StartDate,
        CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE())  AS VARCHAR)+'/03/31'  AS DATE) ELSE CAST( CAST(YEAR(GETDATE())+1 AS VARCHAR)+'/03/31'  AS DATE) END AS EndDate
)

SELECT t.* 
FROM YourTable t
INNER JOIN cte c
ON t.StartDate between c.StartDate AND c.EndDate 
ORDER BY year(t.StartDate)
select t.*,getdate() 
    from @t t
    where   year(startdate) * 100 + month(startdate) >=
        case 
        when  month(getdate()) in (1,2,3) then (year(getdate()) * 100) + 3 - 100
        else  (year(getdate()) * 100) + 3 
        end