对于单个客户:
我能想到的最佳解决方案不是使用分析,而是使用子查询/公用表表达式。 Oracle 通常足够聪明,知道是否将它们转换为临时表,从而降低了多次传递相同数据的成本。
with txns as
(select customer_id
txn_id,
txn_ts
from transaction_table
where customer_id = ?
AND txn_ts >= SYSTIMESTAMP - NUMTODSINTERVAL(10, 'DAY')
)
select customer_id,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(5/1440, 'day'))
as txn_5_min,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(30/1440, 'day'))
as txn_30_min,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(1/24, 'day'))
as txn_1_hour,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(2/24, 'day'))
as txn_2_hour,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(3/24, 'day'))
as txn_3_hour,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(4/24, 'day'))
as txn_4_hour,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(1, 'day'))
as txn_1_day,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(2, 'day'))
as txn_2_day,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(5, 'day'))
as txn_5_day,
(select count(*) from txns
where event_ts >= systimestamp - numtodsinterval(10, 'day'))
as txn_10_day
from customer
WHERE customer_id = ?;
您可以对多客户案例使用类似的实现,尽管效率肯定会受到影响。考虑一下,在您完成检索时,您的 5 分钟级别数据对于所有客户来说是否已经过时。