在Oracle中计算条件累积和

时间:2013-02-20 18:42:22

标签: sql oracle

我正在尝试做的广泛观点是,在预订的日期之前,查看整个系统中有多少尚未发生的预订。这意味着计算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的数据库中的预留数(尚未发生)。 我原来的结果确实有错误。对不起困惑

5 个答案:

答案 0 :(得分:11)

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

Sql Fiddle


编辑:

根据更新的说明,我认为这应该会产生预期的结果:

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"

Sql Fiddle

答案 1 :(得分:4)

您可以使用case sum

来轻松完成此操作。

select booking_date,
       SUM(case when redemption_date >= booking_date then 1 else 0 end)
from bookings b
group by booking_date
order by booking_date

顺便说一下,这不是一个累积的总和。将具有语法:

sum(whatever) over (partition by . . . order by . . . )

它会在每一行上加上计算值。

答案 2 :(得分:2)

这应该可以帮到你找到你想要的东西

SELECT booking_date, SUM(CASE WHEN booking_date >= redemption_date THEN 1 ELSE 0 END) AS number_of_reservations
FROM yourtable
GROUP BY booking_date
ORDER BY booking_date

答案 3 :(得分:1)

尝试这个(我假设你想要所有这些,而不是那些看起来超过一定数量的那些)

select booking_date, count(*) as number_of_reservations
from table_name
group by booking_date order by booking_date

答案 4 :(得分:-2)

这是一个简单的解决方案。

select a.trans_id,
  a.quantity+nvl((select sum(quantity) from table1 where trans_id<a.trans_id),0) quantity 
from table1 a 
order by a.sys_trans_id