我有 table 列,例如 Cycle_code(2 个字符)、cycle_month(2 个字符)、cycle_year(4 个字符)。我怎样才能 select 最后 06 cycle_month 数据?

I have table with columns like Cycle_code (2 char), cycle_month (2 char),cycle_year (4 char). how can I select last 06 cycle_month data?

Initials column where "where" clause is applying are like "Cycle_code" and "Cycle_month" and >"Cycle_year". I want a query which can select last 6 cycle_month data from current cycle month.but >suppose current cycle month is 04 then to find 6 months data I need to search for last year's 2 months ?>also. now in my cycle_year column "where clause" value should be changed wrt to cycle_month. I tried this.

where cycle_code="XX" and
cycle_month in (04,03,02,01,11,12) and
cycle_year ="2020";```

如果我没理解错的话,你可以在year/month连击上使用算术:

where cycle_year * 12 + cycle_month >= extract(year from sysdate) * 12 + extract(month from sysdate) - 5

您可以使用 to_date() 从这些部分重建合法日期并将其用于过滤:

where to_date(cycle_year || '-' || cycle_month || '-01', 'yyyy-mm-dd') 
    >=  trunc(sysdate, 'mon') - interval '6' month

我实际上不建议将您的日期存储为单独的部分,因为当您需要将它们作为日期处理时,这会使事情不必要地复杂化。您可以使用计算列来简化查询:

alter table mytable add 
    mydate as (to_date(cycle_year || '-' || cycle_month || '-01', 'yyyy-mm-dd'))

那么你可以这样做:

where mydate >= trunc(sysdate, 'mon') - interval '6' month