2016-01-06 115 views
0

我想在我的表格中插入每週日期,開始日期總是在星期五,結束日期總是在星期四。我使用此代碼:從星期五開始插入每週日期

CREATE TABLE WEEK AS 
    WITH generator AS (
    SELECT DATE '2015-01-02' + LEVEL - 1 dt 
    FROM dual 
    CONNECT BY LEVEL <= DATE '2016-01-21' - DATE '2015-01-02' + 1 
      ) 
    SELECT to_char(dt, 'YYYY "SEM"IW') "KEY", 
     dt "DATE_START", 
     least(next_day(dt - 1, to_char(DATE '2015-01-08', 'DAY')), 
      last_day(dt)) "DATE_END" 
FROM generator 
WHERE to_char(dt, 'D') = to_char(DATE '2015-01-02', 'D'); 

的代碼工作周在同一個月,但如果我有一個月,到下個月完成日期起始日期,有一個在沒有數據插入我的表。 例如:

Date_ START | DATE_END 

29-05-2015 | 31-05-2015  
05-06-2015 | 11-05-2015 

而不是31-05-2015我應該有2015年4月6日。

回答

1

我認爲下面是你以後有什麼:

with generator as (select  date '2015-05-29' + (level - 1)*7 dt 
        from  dual 
        connect by level <= (date '2016-01-21' - date '2015-05-29')/7 + 1) 
select to_char(dt, 'YYYY "SEM"IW') "KEY", 
     dt "DATE_START", 
     dt + 6 "DATE_END" 
from generator; 

KEY  DATE_START DATE_END 
---------- ---------- ---------- 
2015 SEM22 2015-05-29 2015-06-04 
2015 SEM23 2015-06-05 2015-06-11 
2015 SEM24 2015-06-12 2015-06-18 
2015 SEM25 2015-06-19 2015-06-25 
<snip> 
2016 SEM01 2016-01-08 2016-01-14 
2016 SEM02 2016-01-15 2016-01-21 

這是假設你已經在發電機子查詢中指定的日期已經被確定爲一個星期五。否則,您可以使用類似trunc(<date> - 4, 'iw') + 4trunc(<date> + 3, 'iw') + 4(取決於您是否希望在指定日期包含前一個或下一個星期五)以確保種子日期肯定是星期五。

+0

謝謝!我有你的代碼所需的所有日期 – user3365621

0

也許只是一個選擇,你可以嘗試在這裏分析功能。但如Boniest所建議的 「剛加入天」會更好一些。有 樂趣

WITH generator AS 
    (SELECT DATE '2015-01-02' + LEVEL - 1 dt 
    FROM dual 
    CONNECT BY LEVEL <= DATE '2016-01-21' - DATE '2015-01-02' + 1 
) 
-- select * from generator; 
SELECT TO_CHAR(dt, 'YYYY "SEM"IW') "KEY", 
    dt "DATE_START", 
    lead(dt) over (ORDER BY (dt)) -1 "End Date" 
FROM generator 
WHERE TO_CHAR(dt, 'D') = TO_CHAR(DATE '2015-01-02', 'D'); 

----------------------------------OUTPUT----------------------------------------- 
**KEY  DATE_START End Date** 
2015 SEM18 05/01/2015 05/07/2015 
2015 SEM19 05/08/2015 05/14/2015 
2015 SEM20 05/15/2015 05/21/2015 
2015 SEM21 05/22/2015 05/28/2015 
2015 SEM22 05/29/2015 06/04/2015 

---------------------------------------------------------------------------------- 
相關問題