简体   繁体   English

如何使用Oracle SQL获取sysdate月份中的所有日期?

[英]How do I get all dates from sysdate's month with Oracle SQL?

I try to get a query without parameters to obtain the list of dates from the current month. 我尝试获取不带参数的查询,以获取当前月份的日期列表。

Something like this: 像这样:

SYSDATE = 16/07/15 SYSDATE = 16/07/15

I want the next list: 我想要下一个列表:

01/07/15 15年1月7日
02/07/15 15年2月7日
... ...
30/07/15 30/07/15
31/07/15 31/07/15

Selects all the days for current month 选择当前月份的所有日期

SELECT  TO_CHAR (TRUNC (SYSDATE, 'MM'), 'YYYYMMDD')+(LEVEL - 1) each_date
FROM    DUAL a
CONNECT BY LEVEL < (TO_NUMBER (TO_CHAR (TRUNC (SYSDATE, 'MM') - 1, 'DD'))+1)

Here's what I got to work: 这是我要工作的内容:

SELECT TRUNC(SYSDATE, 'MM') + LEVEL - 1 AS day
FROM dual
CONNECT BY TRUNC(TRUNC(SYSDATE, 'MM') + LEVEL - 1, 'MM') = TRUNC(SYSDATE, 'MM')
;

The key in this query is TRUNC(SYSDATE, 'MONTH') which is the first day of the current month. 此查询中的关键字是TRUNC(SYSDATE, 'MONTH') ,它是当前月份的第一天。
We use hierarchical queries to keep adding one day to the first day of the month until the value is no longer in the current month. 我们使用分层查询将一天中的第一天增加一天,直到该值不再是当前月份。
We use LEVEL - 1 because LEVEL starts from 1 and we need it to start from zero. 我们使用LEVEL - 1因为LEVEL从1开始,我们需要从0开始。

Here's a pseudo-query for what the above query does: 这是上述查询的伪查询:

SELECT (start_of_month + days) AS day
FROM dual
WHILE MONTH_OF(start_of_month + days) = current_month

This query be a bit easier to understand: 这个查询有点容易理解:

SELECT *
FROM
(
    SELECT TRUNC(SYSDATE, 'MM') + LEVEL - 1 AS day
    FROM dual
    CONNECT BY LEVEL <= 32
)
WHERE EXTRACT(MONTH FROM day) = EXTRACT(MONTH FROM SYSDATE)

This should work: 这应该工作:

    select trunc(sysdate, 'MONTH') + rownum - 1
      from dual
connect by rownum <= to_number(to_char(last_day(sysdate), 'DD'));

This is a trick using connect by. 这是使用connect by的技巧。 I truncate the date at the month level, effectively setting it to the 1st day of the month, add a day for each "level" and then filter for any day that occurs outside the month. 我在月份级别截断日期,将其有效地设置为该月的第一天,为每个“级别”添加一天,然后过滤该月份以外发生的任何一天。

select day_of_month
from
(select (level - 1) + trunc(to_date('07/16/2015','MM/DD/YYYY'),'MM') day_of_month
from
dual
connect by level <= 31)
where day_of_month < add_months(trunc(to_date('07/16/2015','MM/DD/YYYY'),'MM'),1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM