Oracle SQL: Get the last eight months of data (with YEAR and MONTH columns)
I have a table that has columns YEAR and MONTH, which are varchars, which have a format like MONTH = '02开发者_开发问答', YEAR = '2011'.
What query can I use to get the last eight months of data, excluding the current month?
Try
where to_date(year || month, 'YYYYMM')
between add_months(trunc(sysdate, 'MM'), -8) and trunc(sysdate)
Try this:
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
)
Another version:
SELECT *
FROM myTable
WHERE year||month IN
(
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, -level), 'RRRRMM') AS yearmonth
FROM dual
CONNECT BY LEVEL < 8
)
Best I can think of is this:
SELECT * FROM table WHERE (MONTH || YEAR) IN ('012011','122010', et cetera)
It is a brute force method, so it is not feasible if you want your query to generalize.
精彩评论