现在我想显示两个日期之间的几个月和几天,例如:
start_date end_date
--------- --------
1-10-2020 2-11-2020
expected output
----------------
MONTH DAYS
10 30
11 2
如何在神谕中得到它?
发布于 2020-03-01 07:04:53
一种选择是创建日历(开始日期和结束日期之间),提取月份(和年份,用于这些日期跨越数年的情况),并计算这些月中的天数。
SQL> with
2 test (start_date, end_date) as
3 (select date '2020-10-01',
4 date '2020-11-02'
5 from dual
6 ),
7 calendar as
8 (select start_date + level - 1 datum
9 from test
10 connect by level <= end_date - start_date + 1
11 )
12 select to_char(datum, 'yyyy.mm') month,
13 count(*) days
14 From calendar
15 group by to_char(datum, 'yyyy.mm')
16 order by 1;
MONTH DAYS
------- ----------
2020.10 31
2020.11 2
SQL>
(顺便说一句,十月有31天,而不是30天)。
发布于 2020-03-01 07:42:52
而不是每天在内部列出,您可以得到所有的(部分)月,然后看看每一个月中有多少天是在范围内的:
with cte (start_date, end_date) as (
select date '2020-10-01', date '2020-11-02' from dual
),
rcte (start_date, end_date, part_month) as (
select start_date, end_date, trunc(start_date, 'MM')
from cte
union all
select start_date, end_date, part_month + interval '1' month
from rcte
where part_month < trunc(end_date, 'MM')
)
select extract(month from part_month) as month_num,
least(end_date, last_day(part_month))
- greatest(start_date, part_month)
+ 1 as num_days
from rcte
order by part_month;
db<>fiddle展示了一些工作。
https://stackoverflow.com/questions/60476360
复制相似问题