【问题标题】:In PostgreSQL, select fiscal year month format as a date column在 PostgreSQL 中,选择会计年度月份格式作为日期列
【发布时间】:2019-10-03 19:05:14
【问题描述】:

我有一个 Postgres 数据库,其中有一个事件发生月份的列。它的格式为 TEXT 列类型,并且在月份名称之前有财政年度,如下所示:

fiscal
-------
20-Jul
20-Aug
20-Jan
20-Apr
20-Feb

假设本例中的财政从 2019 年 4 月开始(并指 2019-2020 财政年度),选择查询如何将其显示为 DATE 列类型? (假设只使用当月的第一天作为日期)

如下所示

fiscal    real_date
--------------------
20-Jul    2019-Jul-1
20-Aug    2019-Aug-1
20-Jan    2020-Jan-1
20-Apr    2019-Apr-1
20-Feb    2020-Feb-1

【问题讨论】:

  • 你的意思是20-Jul应该变成2020-Jul-01吗?不是2019
  • @Andrew,不,因为财政年度“2020”是指从 2019 年 4 月到 2020 年 3 月的年份。所以因为它是“2020 财政年”的 7 月,所以实际月份是 2019 年 7 月.
  • 抱歉,读取失败...

标签: sql postgresql business-intelligence


【解决方案1】:

我认为这实现了你想要的逻辑:

select (case when extract(month from to_date(substr(fm, 4, 3), 'MON')) >= 4
             then to_date('20' || fm, 'YYYY-MON')
             else to_date('20' || fm, 'YYYY-MON') + interval '1 year'
        end)
from (values ('20-JUL'), ('19-FEB')) v(fm);

Postgres 恰好允许您将月份转换为日期。您可以在很久以前获得价值。但是我认为没有任何问题,因为目的只是将字符串转换为数字。

【讨论】:

    【解决方案2】:

    这看起来很可怕,但它似乎到目前为止工作......

    select
    
    case when extract('month' from (to_date(<your column>,'yy-mon'))) > 4
      then (to_date(<your column>,'yy-mon')) + interval '-1' year
    else (to_date(<your column>,'yy-mon'))
                  end
    from
    <your table>
    

    Fiddle example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2023-03-25
      • 2021-12-15
      • 2013-10-26
      • 1970-01-01
      • 2015-06-20
      • 2015-04-29
      相关资源
      最近更新 更多