两个日期之间的周数

时间:2016-02-23 10:02:47

标签: oracle week-number

我试图获取两个日期之间的周数。

例如,在2016年1月1日至2016年2月29日期间,我应该

S01 S02 S03 S04 S05 S06 S07 S08

有可能吗?怎么办呢?

2 个答案:

答案 0 :(得分:3)

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

<强>输出

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

更新 - 有几个月&amp;日期

注意:更改边界以突出显示周数和序列号之间的差异。

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;

<强>输出

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 

答案 1 :(得分:2)

如果您想要日历周编号,那么您可以使用与MTO答案类似的分层方法:

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

如果你想要ISO周,那么使用IW而不是WW,但这是第一周S53(从去年开始)。