在Oracle中,我想获取以下数据:
我能够成功完成第一项:
WHERE CREATE_TIMESTAMP > SYSDATE - 30
但不确定如何实现第二项。我试过了:
WHERE CREATE_TIMESTAMP BETWEEN ((SYSDATE - 395) AND (SYSDATE - 365))
此外,我的CREATE_TIMESTAMP
是timestamp
列。
答案 0 :(得分:1)
如果您只想获取今年或去年同一天的最后30天内的日期清单,那么:
SELECT TRUNC(SYSDATE) - LEVEL + 1
FROM DUAL
CONNECT BY LEVEL <= 30
UNION ALL
SELECT ADD_MONTHS( TRUNC(SYSDATE) - LEVEL + 1, -12 )
FROM DUAL
CONNECT BY LEVEL <= 30
如果您尝试将查询中的数据限制为仅那些日期,则:
WHERE ( date_column BETWEEN sysdate - 30
AND sysdate
OR date_column BETWEEN ADD_MONTHS( sysdate, -12 ) - 30
AND ADD_MONTHS( sysdate, -12 )
)
或者如果您特别担心上述过滤器中从TIMESTAMP
转换为DATE
,那么您可以使用以下功能:
CREATE OR REPLACE FUNCTION TS_ADD_MONTHS(
datetime TIMESTAMP,
months INT
) RETURN TIMESTAMP DETERMINISTIC
AS
p_date CONSTANT DATE := TRUNC( datetime );
BEGIN
RETURN CAST( ADD_MONTHS( p_date, months ) AS TIMESTAMP )
+ ( datetime - p_date );
END;
/
SHOW ERRORS;
然后在您的查询中可以使用:
WHERE ( date_column BETWEEN SYSTIMESTAMP - INTERVAL '30' DAY
AND SYSTIMESTAMP
OR date_column BETWEEN TS_ADD_MONTHS( sysdate, -12 ) - INTERVAL '30' DAY
AND TS_ADD_MONTHS( sysdate, -12 )
)