英文:
Months that ends with 29,30,31 ORACLE
问题
https://stackoverflow.com/questions/75382316/convert-into-date-format-oracle 这个讨论的延续部分中有一个相同的问题。
我在表my_table
中有一个名为c_day
的字段,它接受从1到31的数值。在这个字段中,我需要将210天添加到今天的日期,并将来自发布日期dd.mm.yyyy的c_day
的值插入。例如,我们取今天的日期08.02.2023
,再加上210天,日期落在九月,如果c_day
是20,那么输出应该是20.09.2023
。但如果c_day
等于31,那么当然日期应该被设置为30.09.2023
,因为九月的最后一天是30号。
现在我已经解决了九月份以30号结束且字段接受从1到31的情况。在这种情况下,如何编写条件以便它获取月份的最后一天呢?
我尝试了以下代码,但它不起作用:
SELECT
C_DAY,
LEAST(
TO_DATE(TO_CHAR(TRUNC(SYSDATE) + 210, 'YYYY-MM-') || C_DAY, 'YYYY-MM-DD'),
CASE
WHEN C_DAY < TO_CHAR(LAST_DAY(TRUNC(SYSDATE) + 210), 'DD') THEN
last_day(TO_DATE(TO_CHAR(TRUNC(SYSDATE) + 210, 'YYYY-MM-') || C_DAY, 'YYYY-MM-DD'))
END
) as result
FROM MY_TABLE
ORDER BY 1
英文:
https://stackoverflow.com/questions/75382316/convert-into-date-format-oracle there is an identical question in the continuation of this discussion.
I have a field c_day
in the table my_table
that accepts numeric values from 1 to 31. In this field. I need to add 210 days to today's date, and insert the value from c_day
from the released date dd.mm.yyyy. For example, we take today's date 08.02.2023
and add 210 days to it, the date falls on September, and if c_day
is 20, then the output should be 20.09.2023
. But if c_day
is equal to 31, then of course the date should be set as 30.09.2023
, because the last day of September is 30.
Now I settled on cases where September ends on the 30th, and the field takes values from 1 to 31. How can I write a condition in such cases so that it takes the last day of the month?
I tried this one, but it doesn't work:
SELECT
C_DAY,
LEAST(
TO_DATE(TO_CHAR(TRUNC(SYSDATE) + 210, 'YYYY-MM-') || C_DAY, 'YYYY-MM-DD'),
CASE
WHEN C_DAY < TO_CHAR(LAST_DAY(TRUNC(SYSDATE) + 210), 'DD') THEN
last_day(TO_DATE(TO_CHAR(TRUNC(SYSDATE) + 210, 'YYYY-MM-') || C_DAY, 'YYYY-MM-DD'))
END
) as result
FROM MY_TABLE
ORDER BY 1
答案1
得分: 1
你可以在不进行任何字符串操作的情况下执行它:
SELECT C_DAY,
LEAST(
TRUNC(TRUNC(SYSDATE) + 210, 'MM') + C_DAY - 1,
LAST_DAY(TRUNC(SYSDATE) + 210)
) AS result
FROM MY_TABLE
ORDER BY c_day
对于示例数据,输出如下:
CREATE TABLE my_table ( c_day ) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 31;
输出结果:
C_DAY | RESULT |
---|---|
1 | 2023-09-01 00:00:00 |
2 | 2023-09-02 00:00:00 |
3 | 2023-09-03 00:00:00 |
... | ... |
28 | 2023-09-28 00:00:00 |
29 | 2023-09-29 00:00:00 |
30 | 2023-09-30 00:00:00 |
31 | 2023-09-30 00:00:00 |
英文:
You can can do it without any string manipulation using:
SELECT C_DAY,
LEAST(
TRUNC(TRUNC(SYSDATE) + 210, 'MM') + C_DAY - 1,
LAST_DAY(TRUNC(SYSDATE) + 210)
) AS result
FROM MY_TABLE
ORDER BY c_day
Which, for the sample data:
CREATE TABLE my_table ( c_day ) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 31;
Outputs:
C_DAY | RESULT |
---|---|
1 | 2023-09-01 00:00:00 |
2 | 2023-09-02 00:00:00 |
3 | 2023-09-03 00:00:00 |
... | ... |
28 | 2023-09-28 00:00:00 |
29 | 2023-09-29 00:00:00 |
30 | 2023-09-30 00:00:00 |
31 | 2023-09-30 00:00:00 |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论