我需要创建一个 53 周的列表,分为几个月(这些是零售月份,因此它们对零售业的人来说更有意义)。
我需要以 4-5-4 的间隔重复最多 53 周的列表。
例如,参见sql fiddle
我想在 SQL 语句中写这个而不是有一个表,也不想使用很多联合。我确定有一种使用方法rownum
,connect-by
但我就是想不出逻辑!
我需要创建一个 53 周的列表,分为几个月(这些是零售月份,因此它们对零售业的人来说更有意义)。
我需要以 4-5-4 的间隔重复最多 53 周的列表。
例如,参见sql fiddle
我想在 SQL 语句中写这个而不是有一个表,也不想使用很多联合。我确定有一种使用方法rownum
,connect-by
但我就是想不出逻辑!
这是我的尝试:
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;
我最终使用了以下内容。不理想但有效:
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