oracle sql query to list all the dates of previous month

☆樱花仙子☆ 提交于 2019-11-29 11:09:11

It sounds like you want something like this

SQL> ed
Wrote file afiedt.buf

  1  select to_char( add_months(trunc(sysdate,'MM'),-1) + level - 1,
  2                  'YYYYMMDD' )
  3    from dual
  4  connect by level <=
  5    last_day(add_months(trunc(sysdate,'MM'),-1)) -
  6    add_months(trunc(sysdate,'MM'),-1) +
  7*   1
SQL> /

TO_CHAR(
--------
20101201
20101202
20101203
20101204
20101205
20101206
20101207
20101208
20101209
20101210
20101211
20101212
20101213
20101214
20101215
20101216
20101217
20101218
20101219
20101220
20101221
20101222
20101223
20101224
20101225
20101226
20101227
20101228
20101229
20101230
20101231

31 rows selected.
M Naveed Raza

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)

A bit of add_months would definitely make it better, as in e.g.

select to_char(x,'yyyymmdd') from (
  select add_months(trunc(sysdate,'MONTH'),-1)+rownum-1 x from all_objects
) where x<trunc(sysdate,'MONTH');

This may be a little easier to understand:

select TO_CHAR(d, 'YYYYMMDD')
from (
  select ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -1) + (ROWNUM - 1) d
  from DUAL connect by level <= 31
)
where d < TRUNC(SYSDATE, 'MM')

However, the "connect by level" method is the most clear, and as described here, faster way to generate sequence of numbers. I don't think there is no way to dramatically improve your query.

As far as the right parenthesis is concerned, you are trying to concatenate strings the wrong way:

select TO_CHAR(TRUNC(SYSDATE,'MM')-1,'YYYYMMDD')-(level-1) as

should work:

select TO_CHAR(TRUNC(SYSDATE,'MM')-1,'YYYYMMDD') || '-' || To_Char(level-1) as

Obviously you don't want the concatenation to happen. Therefore, I think you actually want to add the level to the TRUNC()-part

Fix:

select TO_CHAR(TRUNC(SYSDATE,'MM') - 1 + level - 1,'YYYYMMDD') as 
EACH_DATE from dual A connect by level 
< (TO_NUMBER(TO_CHAR(TRUNC(SYSDATE,'MM')-1,'DD'))+1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!