【问题标题】:How can I calculate Financial year from created date using SQLite如何使用 SQLite 从创建日期计算财政年度
【发布时间】:2021-12-17 17:45:56
【问题描述】:

假设我说我的财政年度开始日期是 2000 年 2 月 1 日。 那么财政年度应该是

2019-03-01 to 2020-02-29
2020-03-01 to 2021-02-28
2021-03-01 to 2022-02-28
.
.
.

我想使用 SQLite 显示财政年度的列,如下所示。

Product created Date Financial Year
Apple 2019-05-28 FY 2019-2020
Apple 2020-01-15 FY 2019-2020
Banana 2020-04-22 FY 2020-2021
Mango 2021-10-15 FY 2021-2022

【问题讨论】:

    标签: sqlite concatenation date-arithmetic strftime


    【解决方案1】:

    我怀疑维护一个单独的表格,其中包含自定义财政年度范围以及您要为每个财政年度显示的文本标签:

    financial_years:
    
    start_date | end_date   | label
    2019-03-01 | 2020-02-29 | FY 2019-2020
    2020-03-01 | 2021-02-28 | FY 2020-2021
    2021-03-01 | 2022-02-28 | FY 2021-2022
    

    现在我们需要做的就是将您的产品表加入上表:

    SELECT p.Product, p.created_date, fy.label
    FROM products p
    INNER JOIN financial_years fy
        ON p.created_date BETWEEN fy.start_date AND fy.end_date;
    

    【讨论】:

    • 如何生成财政年度。我有财政年度的开始日期。我们可以编写一些查询来生成财务年度表/视图,并从另一个表中创建日期吗?
    • 我建议您将每个财政年度的自定义日期范围与标签一起存储在单独的表格中。然后,加入这个表。
    【解决方案2】:

    不需要单独的表格。

    你只需要strftime()这个函数:

    SELECT *,
           'FY ' || strftime('%Y', createdDate, '-2 month') || '-' ||
           strftime('%Y', createdDate, '-2 month', '+1 year') FinancialYear
    FROM products;
    

    请参阅demo

    【讨论】:

    • 谢谢,伙计,这就是我要找的东西
    • 我必须做哪些更改才能在单独的列中显示财政年度的开始日期和财政年度的结束日期?
    • @Shambhusharan 检查这个:dbfiddle.uk/…
    【解决方案3】:

    createdDate REALCASE WHEN 的解决方案:

    select Product,
      date(createdDate) as createdDate, 
      case when (abs(strftime('%m', createdDate)) < 3)
           then 'FY ' || cast(strftime('%Y', createdDate) - 1 as text) || '-' || strftime('%Y', createdDate)
           else 'FY ' || strftime('%Y', createdDate) || '-' || cast(strftime('%Y', createdDate) + 1 as text)
      end AS FinancialYear
    from `products`;
    

    查看演示here

    【讨论】:

    • 这也有效。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多