【问题标题】:Query Optimization for my code in Oracle SQL我在 Oracle SQL 中的代码的查询优化
【发布时间】:2020-04-12 13:26:18
【问题描述】:

这是我的代码:

    select 
    (case when c.yr = 2019 and c.mon = 10 then 'October 2019' 
    when c.yr = 2019 and c.mon = 11 then 'November 2019' 
    when c.yr =2019 and c.mon = 12 then 'December 2019' end) as dae 
    from ( 
          select substr(d,-4,4) as yr, substr(d,1,2) as mon 
          from 
          (select '10/11/2019' as d from dual)  )c;                                                                                                                                                                                                                                                                       
`

所以我不想硬编码未来 5 年的日期,有没有让这更容易的函数。

这是我想尝试的示例输入

10/11/2019
11/11/2019
12/11/2019
01/11/2020

预期输出

October 2019
November 2019
December 2019
January 2020

【问题讨论】:

    标签: sql oracle date plsql query-optimization


    【解决方案1】:

    您可以使用to_date() 将字符串转换为日期,然后使用to_char() 将其转换回所需格式的字符串:

    to_char(to_date(d, 'mm/dd/yyyy'), 'Month yyyy')
    

    Demo on DB Fiddle

    with t as (
        select '10/11/2019' d from dual
        union all select '11/11/2019' from dual
        union all select '12/11/2019' from dual
        union all select '01/11/2020' from dual
    )
    select to_char(to_date(d, 'mm/dd/yyyy'), 'Month yyyy') new_dt from t
    
    | NEW_DT | | :------------- | | 2019 年 10 月 | | 2019 年 11 月 | | 2019 年 12 月 | | 2020 年 1 月 |

    【讨论】:

      【解决方案2】:

      使用connect by 生成任意数量的日期。此处 gen_dates CTE 从您的 start_date 开始,每个示例总共返回 4 个月。要增加生成的月数,请将数字 4 增加到更大的数字。

      with gen_dates(date_in) as (
        select add_months('11-OCT-2019', level -1) date_in
        from dual
        connect by level <= 4
      )
      select date_in, to_char(date_in, 'Month yyyy') date_out 
      from gen_dates; 
      
      
      DATE_IN   DATE_OUT      
      --------- --------------
      11-OCT-19 October   2019
      11-NOV-19 November  2019
      11-DEC-19 December  2019
      11-JAN-20 January   2020
      
      4 rows selected.
      

      【讨论】:

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