条件分组记录

时间:2017-05-18 17:49:28

标签: sql oracle

我需要在operation_date操作之前获取PAYMENT的MAX REINSURER记录。通过付款或再保险人对记录进行分组。数据如下:

operation_date | operation
05-17-2012        PAYMENT
05-18-2012        PAYMENT
05-21-2012        PAYMENT
05-25-2012        REINSURER
05-30-2012        PAYMENT
06-07-2012        PAYMENT
06-08-2012        PAYMENT
06-08-2012        REINSURER
06-11-2012        PAYMENT
06-22-2012        REINSURER
07-09-2012        PAYMENT
07-17-2012        REINSURER
07-23-2012        PAYMENT
07-24-2012        PAYMENT
07-27-2012        REINSURER
07-30-2012        PAYMENT
10-31-2012        PAYMENT
11-01-2012        PAYMENT

我需要这个输出:

operation_date | operation
05-21-2012        PAYMENT
05-25-2012        REINSURER
06-08-2012        PAYMENT
06-08-2012        REINSURER
06-11-2012        PAYMENT
06-22-2012        REINSURER
07-09-2012        PAYMENT
07-17-2012        REINSURER
07-24-2012        PAYMENT
07-27-2012        REINSURER
11-01-2012        PAYMENT

我一直在玩分析功能但没有成功。知道如何处理这个吗?

2 个答案:

答案 0 :(得分:3)

您可以使用累积总和生成组,然后对其执行聚合。

select max(operation_date) as operation_date,
    operation
from (
    select t.*,
        sum(case when operation = 'REINSURER' then 1 else 0 end) over (
            order by operation_date, operation
            ) as grp
    from t
    where operation in ('REINSURER', 'PAYMENT')
    ) t
group by grp,
    operation
order by operation_date

Demo

答案 1 :(得分:1)

您需要滞后/领导分析功能而不是聚合分析功能。

select * from ( 
    select a.*,lag(operation_date) over(order by operation_date) p_opr_dt,
      lag(operation) over(order by operation_date) p_opr from operations a 
) where operation = 'REINSURER' and p_opr = 'PAYMENT'