获取财政年度查询中的动态日期范围的逻辑
Posted
技术标签:
【中文标题】获取财政年度查询中的动态日期范围的逻辑【英文标题】:Logic to get dynamic date range in query for Fiscal Year 【发布时间】:2020-02-11 19:26:33 【问题描述】:我需要为不同的日期范围选择数据,具体取决于它运行的当前月份。我有一个存储过程,它将用户提供的日期,即 04/06/2020 接收到变量 @PPE
中。根据该日期的月份部分,我需要查询不同的范围,如财政年度(7 月 1 日至 6 月 30 日)如下所示:我正在使用使用 2020 财政年度的示例。
MONTH(@PPE) Date Range to Query
July 07/01/2019 - 07/01/2019
August 07/01/2019 - 08/31/2019
September 07/01/2019 - 09/30/2019
October 07/01/2019 - 09/30/2019
November 07/01/2019 - 09/30/2019
December 07/01/2019 - 09/30/2019
January 07/01/2019 - 12/31/2019
February 07/01/2019 - 12/31/2019
March 07/01/2019 - 12/31/2019
April 07/01/2019 - 03/31/2020
May 07/01/2019 - 03/31/2020
June 07/01/2019 - 03/31/2020
然后从下一个财政年度(2021 年)开始,将如下所示,然后……
MONTH(@PPE) Date Range to Query
July 07/01/2020 - 07/01/2020
August 07/01/2020 - 08/31/2020
September 07/01/2020 - 09/30/2020
October 07/01/2020 - 09/30/2020
November 07/01/2020 - 09/30/2020
December 07/01/2020 - 09/30/2020
January 07/01/2020 - 12/31/2020
February 07/01/2020 - 12/31/2020
March 07/01/2020 - 12/31/2020
April 07/01/2019 - 03/31/2021
May 07/01/2019 - 03/31/2021
June 07/01/2019 - 03/31/2021
我从这个查询开始,但我在操作正确的 FISCAL_YEAR
时遇到了麻烦,具体取决于 @PPE
日期的月份,因为它跨越 2 年的 4 月和 6 月。
PERIOD
表示会计月份编号,即 July = 1 , August = 2, ....June = 12
DECLARE @PPE datetime; SET @PPE = '04/06/2020'
SELECT COMPANY, DEPTID, FISCAL_YEAR, PERIOD, GH_REPORTID, SUM(GH_HOURS), SUM(GH_DOLLARS)
FROM PS_GH_SLT_ACTUALS
WHERE DEPTID = 55650000
AND GH_REPORTID = 'BA'
AND PERIOD <= CASE WHEN MONTH(@PPE) BETWEEN 1 AND 3 THEN 12
WHEN MONTH(@PPE) BETWEEN 4 AND 6 THEN 3
WHEN MONTH(@PPE) BETWEEN 7 AND 9 THEN 6
WHEN MONTH(@PPE) BETWEEN 10 AND 12 THEN 9
END
-- AND PERIOD <= 7 ???
AND FISCAL_YEAR = CASE WHEN MONTH(@PPE) BETWEEN 1 AND 3 THEN YEAR(@PPE)
WHEN MONTH(@PPE) BETWEEN 4 AND 6 THEN ....???
GROUP BY COMPANY, DEPTID, FISCAL_YEAR, PERIOD, GH_REPORTID
【问题讨论】:
一般来说,日期或日历表是这种查询的方式。该表将以某种方式包括财政年度。查看数据仓库日期维度表。 【参考方案1】:如果您的会计年度已经是格式,那么您可以使用以下和条件:
FISCAL_YEAR = CASE WHEN MONTH(@PPE) BETWEEN 1 AND 6 THEN YEAR(@PPE)
ELSE YEAR(@PPE)+1 END
根据您的数据,上述条件应假设 2019 年 7 月至 2020 年 6 月称为 2020 财年。希望这会有所帮助。
【讨论】:
以上是关于获取财政年度查询中的动态日期范围的逻辑的主要内容,如果未能解决你的问题,请参考以下文章