【问题标题】:How to get the date of the upcoming January?如何获得即将到来的一月的日期?
【发布时间】:2019-06-30 10:34:20
【问题描述】:

我正在使用 DB2 并在一个表上编写一个 SQL 查询,其中每个下个月都有一个列。像,一月,二月,三月,四月,五月等总共12个。

数据是未来 12 个月的预测销售额。每晚都会重新计算。

例如,如果当前月份是 2019 年 11 月,则 11 月列包含 2019 年 11 月的预测,12 月列包含 2019 年 12 月的预测等。但是,1 月列包含 2020 年 1 月的数据。

如何在 SQL 中获取该列所代表的下个月的日期?

我需要一个像 GetNextJanuary() 这样的函数,如果今年使用它会返回 20200101,而 GetNextDecember() 会返回 20191201 等。但是,如果我今天使用 GetNextJune(),它应该返回 20190601(当前月份)。

单独使用 SQL 是否可行?

【问题讨论】:

    标签: sql db2


    【解决方案1】:

    我们可以将这个问题表述为在输入日期上加一年,然后截断到那一年的开始:

    SELECT
        DATE_TRUNC('YEAR', ADD_YEARS(CURRENT_DATE, 1))
    FROM dual;
    

    【讨论】:

      【解决方案2】:

      你可以使用case逻辑:

      select (case when month(current date) <= 1
                   then to_date(year(current date) || '01-01', 'YYYY-MM-DD')
                   else to_date(year(current date) + 1 || '01-01', 'YYYY-MM-DD')
              end) as jan_start_of_month,
             (case when month(current date) <= 2
                   then to_date(year(current date) || '02-01', 'YYYY-MM-DD')
                   else to_date(year(current date) + 1 || '02-01', 'YYYY-MM-DD')
              end) as feb_start_of_month,
             . . .
      

      【讨论】:

        【解决方案3】:
        create or replace function GetNextMonth(p_month int)
        returns date
        deterministic
        no external action
        return 
          date(digits(dec(year(current date), 4))||'-'||digits(dec(p_month, 2))||'-01')
        + (case when p_month < month(current date) then 1 else 0 end) years;
        
        select *
        from table(values 
        (getnextmonth(1), getnextmonth(12), getnextmonth(6))
        ) t (jan, dec, june);
        
        JAN        DEC        JUNE
        ---------- ---------- ----------
        2020-01-01 2019-12-01 2019-06-01
        

        逻辑是:如果传递的月份号(p_month)小于当前月份,那么我们将传递的月份号的当年第1天构造的日期加上1年,0否则几年。

        【讨论】:

        • 嗯....我可能只是在某个“0”日期('2000-01-01',最有可能)上加上年份和月份,而不是乱用数字。
        • 您的解决方案能比这个更快或更简单吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-12
        • 1970-01-01
        • 1970-01-01
        • 2017-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多