创建周列表,按月间隔列出类别

时间:2013-07-22 04:08:34

标签: sql oracle

我需要创建一个53周的列表,分为几个月(这些是零售月份,因此它们对零售业的人更有意义)。

我需要列表重复53周,间隔4-5-4。

例如,请参阅sql fiddle

我想在SQL语句中写这个,而不是有一个表,也没有使用大量的联合。我确信有一种方法可以使用rownumconnect-by,但我无法想到逻辑!

2 个答案:

答案 0 :(得分:0)

这是我的尝试:

SELECT DISTINCT to_char(l_date,'WW') week_id ,
      to_char(l_date, 'mm') month_id
FROM
     (SELECT to_date('01/jan/2013', 'dd/mm/yyyy')+LEVEL-1 l_date
     FROM dual
          CONNECT BY LEVEL <= 365
     ORDER BY 1
     )
ORDER BY WEEK_ID;

编辑根据您的SQL FIDDLE表:

SELECT week_id,     MAX(month_id)
FROM
     (SELECT DISTINCT TO_CHAR(l_date,'WW') week_id ,
          TO_CHAR(l_date, 'mm') month_id
     FROM
          (SELECT TRUNC(SYSDATE, 'year')+LEVEL-1 l_date
          FROM dual
               CONNECT BY LEVEL <= 365
          )
     )
GROUP BY week_id 
     ORDER BY WEEK_ID;

答案 1 :(得分:0)

我最终使用了以下内容。不理想但它有效:

SELECT ROWNUM AS WEEK_ID, 1 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 4
UNION ALL
SELECT ROWNUM+4 AS WEEK_ID, 2 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 5
UNION ALL
SELECT ROWNUM+9 AS WEEK_ID, 3 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 4
UNION ALL
SELECT ROWNUM+13 AS WEEK_ID, 4 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 4
UNION ALL
SELECT ROWNUM+17 AS WEEK_ID, 5 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 5
UNION ALL
SELECT ROWNUM+22 AS WEEK_ID, 6 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 4
UNION ALL
SELECT ROWNUM+26 AS WEEK_ID, 7 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 4
UNION ALL
SELECT ROWNUM+30 AS WEEK_ID, 8 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 5
UNION ALL
SELECT ROWNUM+35 AS WEEK_ID, 9 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 4
UNION ALL
SELECT ROWNUM+39 AS WEEK_ID, 10 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 4
UNION ALL
SELECT ROWNUM+43 AS WEEK_ID, 11 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 5
UNION ALL
SELECT ROWNUM+48 AS WEEK_ID, 12 AS MONTH_ID
FROM DUAL
CONNECT BY ROWNUM <= 5