我有一个像酒店系统一样工作的表,包含入住和退房日期。 我在这里想做的是,我想查看一个月内有多少天可用/免费。 例如;
姓名 | 签到 | 签出 |
---|---|---|
乔伊·佐罗门 | 2023年5月8日 | 2023年8月15日 |
猎人佐罗蒙 | 2023年8月15日 | 2023年8月26日 |
巴里·艾伦 | 2023年2月9日 | 2023年5月9日 |
我需要输出看起来像这样;
月 | 免费_天数 |
---|---|
08/2023 | 8 |
09/2023 | 26 |
提前谢谢大家!!!
这是一种选择;阅读代码中的注释:
SQL> with
2 test (name, check_in, check_out) as
3 -- this is your sample table
4 (select 'Joey Zolomon' , date '2023-08-05', date '2023-08-15' from dual union all
5 select 'Hunter Zolomon', date '2023-08-15', date '2023-08-26' from dual union all
6 select 'Barry Allen' , date '2023-09-02', date '2023-09-05' from dual
7 ),
8 checked as
9 -- non-available dates
10 (select check_in + column_value - 1 datum
11 from test cross join table(cast(multiset(select level from dual
12 connect by level <= check_out - check_in + 1
13 ) as sys.odcinumberlist))
14 ),
15 calendar as
16 -- calendar for the whole year
17 (select trunc(sysdate, 'yyyy') + level - 1 datum
18 from dual
19 connect by level <= add_months(trunc(sysdate, 'yyyy'), 12) - trunc(sysdate, 'yyyy')
20 ),
21 available as
22 -- available dates are calculated as [all days in a year] MINUS [all non-available dates]
23 (select k.datum from calendar k
24 minus
25 select c.datum from checked c
26 )
27 -- finally, aggregate number of free (available) dates per every month
28 select to_char(a.datum, 'mm') month,
29 count(*) free_days
30 from available a
31 group by to_char(a.datum, 'mm')
32 order by to_char(a.datum, 'mm');
结果:
MONTH FREE_DAYS
----- ----------
01 31
02 28
03 31
04 30
05 31
06 30
07 31
08 9 --> you said it should be 8; nope. August has 31 days
09 26
10 31
11 30
12 31
12 rows selected.
SQL>