小编典典

在Oracle中计算条件累积总和

sql

我正在尝试做的事情的广泛视角是,在预订系统被预订之日,找出整个系统中尚未进行的预订。这意味着计算存在的所有记录的数量,这些记录的后缀redemption_date等于(或等于)booking_date,按分组booking_date。请参阅以下假设示例,以获得更好的解释:

redemption_date      booking_date
2013-01-01           2013-01-01
2013-01-06           2013-01-01
2013-01-06           2013-01-01
2013-01-07           2013-01-02
2013-01-08           2013-01-03
2013-01-09           2013-01-04
2013-01-10           2013-01-05
2013-01-10           2013-01-05
2013-01-10           2013-01-05
2013-01-10           2013-01-05
2013-01-10           2013-01-05
2013-01-11           2013-01-05

我想要结果:

booking_date         number_of_reservations
2013-01-01           3
2013-01-02           3
2013-01-03           4
2013-01-04           5
2013-01-05           11

但是我对如何构造查询完全不满意。有小费吗?谢谢!

编辑:为明确起见,number_of_reservations应该是该日期的预订数量,以及该日期之后几天的预订数量。换句话说,number_of_reservations是截至booking_date(尚未发生)的数据库中的保留数。我的原始结果确实有误。对困惑感到抱歉


阅读 226

收藏
2021-05-23

共1个答案

小编典典

SELECT
booking_date,
COUNT(
CASE WHEN redemption_date >= booking_date
THEN 1 END
) AS number_of_reservations
FROM
Reservations
GROUP BY
booking_date

sqlfiddle


编辑:

基于更新的描述,我相信这应该能够获得预期的结果:

SELECT DISTINCT
    r."booking_date",
    (SELECT COUNT(*) 
     FROM reservations r2 
     WHERE 
         r2."booking_date" <= r."booking_date"
         AND r2."redemption_date" >= r."booking_date"
    ) AS number_of_reservations
FROM
    Reservations r
ORDER BY r."booking_date"

sqlfiddle

2021-05-23