SQL查询以查找特定格式的月份的最后一天-Yyyy/mm
我有以下几个月的格式 -
2022 / 12
2021 / 03
2020 / 02
YYYY / MM
我想找出这些月份的最后一天。 IE 2022/12/31,2021/03/31,2020/02/28
我正在使用以下代码 -
to_date(to_char(:p_month||'01/', 'yyyy / mm/dd'), 'yyyymmdd')
但它丢弃了无效的格式错误。
I have months in the following format -
2022 / 12
2021 / 03
2020 / 02
YYYY / MM
I want to find out the last day of these months. i.e. 2022/12/31, 2021/03/31 , 2020/02/28
I am using the below code -
to_date(to_char(:p_month||'01/', 'yyyy / mm/dd'), 'yyyymmdd')
but it is throwing an invalid format error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了获得所需的结果,您需要采取以下步骤:
可能有多种方法可以做到这一点。例如,您可以执行以下操作:
第一部分:
从您的table;
中选择替换(datepart,''''); 删除whitespaces ...第二部分:
select> select to_date(repleast to_date(repleast(datepart,datepart, '','),'yyyy/mm')来自您的tourable;
以将列作为日期和...第三部分:
选择last_day(to_date(to_date(repleast(datepart,'''''','') ),'yyyy/mm'))从yourtable;
获得此日期的最后一天。请参阅此处的工作示例:
There are following steps you need to take in order to get your desired result:
There is likely more than one way to do this. As example you can do following:
1st part:
SELECT REPLACE(datepart,' ','') FROM yourtable;
to remove whitespaces...2nd part:
SELECT TO_DATE(REPLACE(datepart,' ',''),'YYYY/MM') FROM yourtable;
to cast your column as date and...3rd part:
SELECT LAST_DAY (TO_DATE(REPLACE(datepart,' ',''),'YYYY/MM')) FROM yourtable;
to get the last day of the month for this date.Please see the working example here: db<>fiddle
首先,您需要将输入字符串转换为日期 - 因此,您应用的第一个功能应为
to_date
(尝试尝试错误的顺序中的两个转换)。 Oracle耐受输入字符串中不需要的空格;to_date
接受不完整的格式,为丢失的组件提供默认格式。因此,
to_date(:p_month,'yyyy/mm')
将返回一个月的第一天(默认值:dd = 1
以及HH24:MI:SS = 00:00:00
)。然后,您可以将
last_day
应用于此结果,如果需要,请使用to_char
将其转换回字符串。这样:对其进行测试:
顺便说一句,您遇到的具体错误是因为您将串联的斜杠放在错误的位置。您的串联
01/
而不是/01
,因此您的字符串变成2022/1201/
而不是2022/2022/12/01 。 Oracle可以容忍不必要的空间,但是它不能与错误的位置的定界符配合使用。
First you need to convert the input string to a date - so the first function you apply should be
to_date
(you have the two conversions in the wrong order in your attempt). Oracle is tolerant of unneeded spaces in the input string; andto_date
accepts incomplete formats, supplying defaults for the missing components.So,
to_date(:p_month, 'yyyy/mm')
will return the first day of the month (that's the default:dd = 1
, as well ashh24:mi:ss = 00:00:00
).Then you can apply
last_day
to this result, and if needed, convert back to a string usingto_char
. Like this:Testing it:
By the way, the specific error you got was because you put the concatenated slash in the wrong place. You concatenated
01/
instead of/01
, so your string became2022 / 1201/
instead of2022 / 12/01
. Oracle tolerates unnecessary spaces, but it can't work with delimiters in the wrong place.