【问题标题】:Calcluate and insert financial years with its financial period, month, start and end date for 20 years计算并插入财政年度及其财政期间、月份、开始和结束日期为 20 年
【发布时间】:2019-07-04 00:11:49
【问题描述】:

我需要在我的数据库中生成 20 年的日期数据。它应该计算财务开始月份(假设 2019 年 7 月),然后计算开始日期(7 月 1 日)和结束日期(7 月 31 日)和财政年度期间(7 期)。然后它应该找到从 7 月开始递增 20 年的所有月份。

应该是这样的

financial_year 月期 start_date end_date

  1. 2019年7月07日 2019/07/01 2019/07/31
  2. 2019 年 8 月 08 日 2019/08/01 2019/08/31
  3. ....
  4. ....
  5. 2039

谁能帮我解决这个问题?

非常感谢。

【问题讨论】:

  • 什么问题?你所做的只是敲出一些参数。你试过什么?失败点是什么?您还需要解释诸如period of 7 之类的事情...一年中有 7 个财务期吗?看起来不像你说的第 7 期,7 月是开始月份
  • @ŇɏssaPøngjǣrdenlarp 我正在寻找可能的解决方案。我无法决定如何解决这个问题,这就是寻求帮助的原因。我无法决定这是否可以仅在 SQL 中完成或需要额外的东西。
  • 您想在 C# 或 SQL 中执行此操作吗?你尝试过什么吗?你在这方面面临什么问题?暗示。将开始日期设为 7 月 1 日,并使用 DateTime.AddMonths 获取下个月的开始日期。使用循环重复执行此操作
  • 下次尝试上网搜索一下。这是关于构建calendar table 的讨论
  • @ChetanRanpariya 谢谢你的逻辑。我正在执行相同的逻辑来生成日期。

标签: c# sql-server datetime


【解决方案1】:
declare @year int, @month int
SELECT @year = 2019, @month = 7

;with cte as (
    SELECT DATEFROMPARTS(@year, @month, 1) start_date, 1 as cnt
    union all 
    SELECT DATEADD(MONTH, 1, start_date), cnt + 1
    FROM cte
    WHERE cnt < 240
),
cte2 as (
    SELECT start_date, 
        DATEADD(day, -1, DATEADD(month, 1, start_date)) end_date,
        DATEPART(YEAR, start_date) year, 
        DATENAME(MONTH, start_date) month,
        DATEPART(MONTH, start_date) period  
    FROM cte
)
select year, month, 
    RIGHT('0' + cast(period as varchar(2)), 2) as period,
    start_date, 
    end_date
from cte2
option(maxrecursion 0)

返回:

year    month       period  start_date  end_date
2019    July        07      2019-07-01  2019-07-31
2019    August      08      2019-08-01  2019-08-31
2019    September   09      2019-09-01  2019-09-30
...
2039    April       04      2039-04-01  2039-04-30
2039    May         05      2039-05-01  2039-05-31
2039    June        06      2039-06-01  2039-06-30

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多