我有一个包含YEAR和MONTH列的表,它们是varchars,格式类似MONTH ='02',YEAR ='2011'。
我可以用什么查询来获取最近八个月的数据,不包括当月?
答案 0 :(得分:6)
尝试
where to_date(year || month, 'YYYYMM')
between add_months(trunc(sysdate, 'MM'), -8) and trunc(sysdate)
答案 1 :(得分:3)
试试这个:
SELECT *
FROM myTable
WHERE (year, month) IN
(
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, -level), 'RRRR') AS year,
TO_CHAR(ADD_MONTHS(SYSDATE, -level), 'MM') AS month
FROM dual
CONNECT BY LEVEL < 8
)
另一个版本:
SELECT *
FROM myTable
WHERE year||month IN
(
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, -level), 'RRRRMM') AS yearmonth
FROM dual
CONNECT BY LEVEL < 8
)
答案 2 :(得分:0)
我能想到的最好是:
SELECT * FROM table WHERE (MONTH || YEAR) IN ('012011','122010', et cetera)
这是一种蛮力方法,因此如果您希望查询一般化,则不可行。