我无法绕过如何编写此查询来计算酒店的入住率,然后按日期列出结果。请考虑名为reservation的表中的以下类型的数据:
Arrival Departure Guest Confirmation
08/01/2015 08/05/2015 John 13234
08/01/2015 08/03/2015 Bob 34244
08/02/2015 08/03/2015 Steve 32423
08/02/2015 08/02/2015 Mark 32411
08/02/2015 08/04/2014 Jenny 24422
输出数据理想情况如下:
Date Occupancy
08/01/2015 2
08/02/2015 4
08/03/2015 2
08/04/2015 1
08/02/2015 0
查询应该能够将日期范围用作变量。我很难找到最明显的方法,如何每晚都能获得点数并按日期吐出来。
答案 0 :(得分:1)
您可以先生成日期列表。在Oracle中,您可以使用connect by
执行此操作。这将进行递归查询。例如,要获得接下来的30天,您可以选择今天并保持连接,直到您获得所需的天数。 level
表示递归级别。
select trunc(sysdate) + level - 1 as THEDATE
from dual
connect by level <= 30;
在该列表中,您可以查询该期间每天的预订数量:
select THEDATE,
(select count(*)
from reservations r
where r.Arrival >= THEDATE and
r.Departure < THEDATE) as RESERVATIONCOUNT
from
( select trunc(sysdate) + level - 1 as THEDATE,
from dual
connect by level <= 30)
除了获得固定数量的日期之外,您还可以在那里获得另一个值,例如,将来至少 30天,但如果稍后有预订则会进一步... :
select THEDATE,
(select count(*)
from reservations r
where r.Arrival >= THEDATE and
r.Departure < THEDATE) as RESERVATIONCOUNT
from
( select trunc(sysdate) + level - 1 as THEDATE,
from dual
connect by
level <= greatest(30, (select trunc(max(DEPARTURE) - sysdate)
from reservations)))