Oracle sql - 获取两个日期之间的月份 ID

时间:2021-07-19 07:40:52

标签: sql oracle

我有日期范围,例如。 “2021-01-05”和“2021-02-10”。一月和二月两个月。

需要结果:

Months
------
1
2

2 个答案:

答案 0 :(得分:2)

您想遍历几个月。这是通过 SQL 中的递归查询完成的:

with months (month_start_date) as
(
  select trunc(:start_date, 'month') from mytable
  union all
  select month_start_date + interval '1' month
  from months
  where month_start_date < trunc(:end_date, 'month')
)
select
  extract(year from month_start_date) as year,
  extract(month from month_start_date) as month
from months
order by month_start_date;

答案 1 :(得分:0)

您可以使用 Oracle 必须使用的 EXTRACT 函数来实现这一点。在您的情况下,它应该类似于:

SELECT EXTRACT (month FROM date_column) as "Months"

有关此功能的更多信息,您可以查看文档 here