[英]Query Optimization for my code in Oracle SQL
Here is my code:这是我的代码:
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;
`
So I don't want to hard code the dates for the next 5 years, Is there a function that makes this easier.所以我不想对未来 5 年的日期进行硬编码,是否有一个功能可以使这更容易。
Here is the Sample Input I want to try这是我想尝试的示例输入
10/11/2019
11/11/2019
12/11/2019
01/11/2020
Expected Output预期产出
October 2019
November 2019
December 2019
January 2020
You could use to_date()
to turn your string to a date, and then convert it back to a string in the desired format with to_char()
:您可以使用to_date()
将字符串转换为日期,然后使用to_char()
将其转换回所需格式的字符串:
to_char(to_date(d, 'mm/dd/yyyy'), 'Month yyyy')
Demo on DB Fiddle : 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 | | :------------- | | October 2019 | | November 2019 | | December 2019 | | January 2020 |
Use connect by
to generate as many dates as you want.使用connect by
生成任意数量的日期。 Here the gen_dates CTE starts with your start_date and returns a total of 4 months per your example.此处 gen_dates CTE 以您的 start_date 开始,并返回每个示例总共 4 个月的时间。 To increase the number of months to generate, increase the number 4 to a higher number.要增加要生成的月数,请将数字 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.