簡體   English   中英

如何在 Oracle SQL 中按順序匹配當前和上個月的日期?(例如 1-jun as monday 與 4th jun monday 匹配)

[英]How to match days for current and previous months sequentially in Oracle SQL?( e.g. 1-jun as monday is matched with 4th jun of monday)

讓我們考慮 6 月和 5 月,6 月 1 日是星期一,然后我會檢查 5 月的第一個星期一,它是 5 月 4 日。 像那樣,我想依次匹配所有其他日子。

我是這樣理解這個問題的:

  • curmon CTE 創建當前月份
  • prevmon CTE 創建上個月
  • 在最終查詢(第 13 行向前)中,關鍵NEXT_DAY function

SQL> with
  2  curmon as
  3    (select trunc(sysdate, 'mm') + level - 1 as datum
  4     from dual
  5     connect by level <= last_day(sysdate) - trunc(sysdate, 'mm') + 1
  6    ),
  7  prevmon as
  8    (select trunc(add_months(sysdate, -1), 'mm') + level - 1 as datum
  9     from dual
 10     connect by level <= last_day(add_months(sysdate, -1)) -
 11                         trunc(add_months(sysdate, -1), 'mm') + 1
 12    )
 13  select to_char(c.datum, 'dd.mm.yyyy, dy') cdatum,
 14         --
 15         to_char(next_day(p.datum, to_char(c.datum, 'dy')), 'dd.mm.yyyy, dy') result
 16  from curmon c join prevmon p on to_char(c.datum, 'dd') = to_char(p.datum, 'dd')
 17  order by c.datum;

CDATUM          RESULT
--------------- ---------------
01.06.2020, mon 04.05.2020, mon
02.06.2020, tue 05.05.2020, tue
03.06.2020, wed 06.05.2020, wed
04.06.2020, thu 07.05.2020, thu
05.06.2020, fri 08.05.2020, fri
06.06.2020, sat 09.05.2020, sat
07.06.2020, sun 10.05.2020, sun
08.06.2020, mon 11.05.2020, mon
09.06.2020, tue 12.05.2020, tue
10.06.2020, wed 13.05.2020, wed
11.06.2020, thu 14.05.2020, thu
12.06.2020, fri 15.05.2020, fri
13.06.2020, sat 16.05.2020, sat
14.06.2020, sun 17.05.2020, sun
15.06.2020, mon 18.05.2020, mon
16.06.2020, tue 19.05.2020, tue
17.06.2020, wed 20.05.2020, wed
18.06.2020, thu 21.05.2020, thu
19.06.2020, fri 22.05.2020, fri
20.06.2020, sat 23.05.2020, sat
21.06.2020, sun 24.05.2020, sun
22.06.2020, mon 25.05.2020, mon
23.06.2020, tue 26.05.2020, tue
24.06.2020, wed 27.05.2020, wed
25.06.2020, thu 28.05.2020, thu
26.06.2020, fri 29.05.2020, fri
27.06.2020, sat 30.05.2020, sat
28.06.2020, sun 31.05.2020, sun
29.06.2020, mon 01.06.2020, mon
30.06.2020, tue 02.06.2020, tue

30 rows selected.

SQL>

由於您報告的錯誤(“無效的列別名”),這是您的數據庫版本(它是什么?10g?)不支持這個:

with curmon (datum) as         --> "datum" here is what Oracle complains about
  (select sysdate from dual)

但你必須把它寫成

with curmon as
  (select sysdate as datum from dual)        --> alias moved here

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM