4

我正在尝试做的事情的广泛观点是找出在预订日期之前整个系统中有多少尚未发生的预订。这意味着计算存在于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 数据库中的预订数量(尚未发生)。我原来的结果确实有错误。对困惑感到抱歉

4

5 回答 5

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 小提琴


编辑:

根据更新的描述,我相信这应该会产生预期的结果:

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 小提琴

于 2013-02-20T18:44:47.140 回答
4

您可以使用casewith轻松完成此操作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 . . . )

它会在每一行上放置一个计算值。

于 2013-02-20T18:44:03.620 回答
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
于 2013-02-20T18:45:12.707 回答
1

试试这个(我假设你想要所有这些,而不是出现超过一定数量的)

select booking_date, count(*) as number_of_reservations
from table_name
group by booking_date order by booking_date
于 2013-02-20T18:44:28.997 回答
-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
于 2013-09-27T11:16:05.187 回答