我的一周从星期六开始,到星期五结束。例如:6-30-2018是我一周的第一天,而7月6日是最后一天。
select trunc(sysdate,'IW') + Level - (1+ trunc(sysdate) - trunc(sysdate, 'IW'))
from dual connect by level < 8;
当我在一周中进行上述查询时,结果会不断变化。我需要它保持不变。
7月5日,它返回以下。 7月4日,它返回了不同的结果。它随着sysdate的变化而变化。
TRUNC(SYSDATE,'IW')+LEVEL-(1+TRUNC(SYSDATE)-TRUNC(SYSDATE,'IW'))
29-JUN-2018 00:00:00
30-JUN-2018 00:00:00
01-JUL-2018 00:00:00
02-JUL-2018 00:00:00
03-JUL-2018 00:00:00
04-JUL-2018 00:00:00
05-JUL-2018 00:00:00
SELECT TRUNC(to_date('08-Jul-2018', 'dd-Mon-yyyy'), 'IW') + Level - (1+ TRUNC(to_date('08-Jul-2018', 'dd-Mon-yyyy'), 'IW') - TRUNC(to_date('08-Jul-2018', 'dd-Mon-yyyy'), 'IW'))
FROM dual
CONNECT BY level <= 8; --great
如果我对此进行硬编码,结果将保持不变。有什么办法虽然看起来可行,但我不必对日期进行硬编码。
谢谢
答案 0 :(得分:0)
这不是很优雅,但似乎可以满足您的需求:
WITH "Week Spans" AS
(
SELECT
NEXT_DAY(TRUNC(SYSDATE,'YY')-1,'Saturday') + ((LEVEL - 1) * 7) + 00 AS "Saturday"
,NEXT_DAY(TRUNC(SYSDATE,'YY')-1,'Saturday') + ((LEVEL - 1) * 7) + 07 - (1 / (24*60*60)) AS "Following Friday"
FROM dual
CONNECT BY LEVEL < 53
)
SELECT
(
SELECT "Saturday"
FROM "Week Spans"
WHERE SYSDATE BETWEEN "Saturday" AND "Following Friday"
) + (LEVEL - 1) AS "Week Day"
FROM dual
CONNECT BY LEVEL < 8
;