Oracle月年临时表

时间:2018-09-19 04:09:45

标签: oracle calendar

我试图创建一个可以在计算中与之联系的月,年临时表,但是我遇到了一些问题。由于限制,我无法创建全局临时表,因此必须依赖以下类型的查询。

WITH Months AS
(
SELECT LEVEL -1 AS ID
FROM DUAL
CONNECT BY LEVEL <=264
)
(SELECT 
ROWNUM AS MO_SYS_ID,
TO_CHAR(ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), ID), 'YYYY'||'MM') AS MO_NM,
TO_CHAR(ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), ID), 'MON') AS MO_ABBR_NM,
TO_CHAR(ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), ID), 'MONTH') AS MO_FULL_NM,
TO_CHAR(ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), ID), 'MM')AS MO_NBR,
TO_CHAR(ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), ID), 'YYYY') AS YR_NBR 
from Months;

我真正需要做的是将它插入我可以回忆起的temp表中。不幸的是,我没有其他表可以使用的任何字段。我需要显示1999年以来的264个月。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以像这样计算表表达式中的日期列:

WITH Months AS (
    SELECT LEVEL -1 AS ID, ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), LEVEL -1) as dt
    FROM DUAL
    CONNECT BY LEVEL <=264
    )
SELECT *
from Months

如果您尝试创建日期范围,则可以执行以下操作:

WITH Months AS (
    SELECT LEVEL -1 AS ID
         , ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), LEVEL -1) as start_dt
         , ADD_MONTHS(TO_DATE('01/01/1999', 'DD/MM/YY'), LEVEL ) as end_dt
    FROM DUAL
    CONNECT BY LEVEL <=264
    )
SELECT *
from yourtable t
inner join Months m on t.somecol >= m.start_dt and  t.somecol < m.end_dt