Week numbers between two dates

扶醉桌前 提交于 2019-12-11 10:50:26

问题


I'm trying to get the week numbers between two dates.

For example, between dates 01/01/2016 and 29/02/2016 I should have

S01 S02 S03 S04 S05 S06 S07 S08

Is it possible? How can it be done?


回答1:


SELECT 'S' || LPAD( LEVEL, 2, '0' )
FROM   DUAL
CONNECT BY DATE '2016-01-01' + ( LEVEL - 1 ) * 7 <= DATE '2016-02-29';

Output:

'S'||LPAD(LEVEL,2,'0')
----------------------
S01                    
S02                    
S03                    
S04                    
S05                    
S06                    
S07                    
S08                    
S09  

Update - with months & dates:

Note: changed bounds to highlight difference between week number and sequence number.

WITH bounds AS (
  SELECT DATE '2016-03-01' AS lower_bound,
         DATE '2016-04-30' AS upper_bound
  FROM   DUAL
),
weeks AS (
  SELECT LEVEL AS id,
         lower_bound + (LEVEL - 1) * 7 AS week_date
  FROM   bounds
  CONNECT BY lower_bound + (LEVEL - 1) * 7 <= upper_bound
)
SELECT 'S' || LPAD( id, 2, '0' ) AS id,
       'W' || TO_CHAR( week_date, 'WW' ) AS week,
       'M' || TO_CHAR( week_date, 'MM' ) AS month,
       week_date
FROM   weeks;

Output:

ID  WEEK MONTH WEEK_DATE
--- ---- ----- ---------
S01 W09  M03   01-MAR-16 
S02 W10  M03   08-MAR-16 
S03 W11  M03   15-MAR-16 
S04 W12  M03   22-MAR-16 
S05 W13  M03   29-MAR-16 
S06 W14  M04   05-APR-16 
S07 W15  M04   12-APR-16 
S08 W16  M04   19-APR-16 
S09 W17  M04   26-APR-16 



回答2:


If you want the calendar week numbers then you can use a similar hierarchical approach to MTO's answer:

select distinct 'S' || to_char(date '2016-01-01' + level -1, 'WW') as week_num
from dual
connect by level <= date '2016-02-29' - date '2016-01-01'
order by week_num;

WEE
---
S01
S02
S03
S04
S05
S06
S07
S08
S09

If you want ISO weeks then use IW instead of WW, but that makes the first week S53 (from last year).



来源:https://stackoverflow.com/questions/35574362/week-numbers-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!