具有条件的Oracle排名()

时间:2015-10-27 17:59:11

标签: oracle rank

我想检查客户在第一件产品之后购买第二件产品时的行为(没有拖欠)(他们向我们借钱购买手机)。

我的主管建议创建一个像

这样的表格
Client_id  Contract_date  Contract_id  no_days_pd Rank
1          01-Jan-2015    123          (null)     1
1          01-May-2015    456          don't care 2
1          01-Aug-2015    789          don't care 3

并检查仅具有等级= 2的合同。在此表中,no_days_pd表示截止日期的天数,null表示在所有分期中没有拖欠。

我可以在Oracle中使用rank()函数吗?我怎样才能在等级上施加一些条件,比如

when product = 'Mobile' and no_days_pd is null then rank = 1

我陷入困境,如何让它继续排名= 2,3,我想order by Contract_date确保第2级合同是在第一份没有拖欠的合同之后。

非常感谢!!

1 个答案:

答案 0 :(得分:1)

试试这个:

已编辑以检查上一份合约的days_past_due

with thetable as (
select 1 client_id,      to_date('01-Jan-2015','dd-mon-yyyy')  contract_Date,  123  contract_id ,  null days_past_due from dual union
select 1 client_id,      to_date('01-May-2015','dd-mon-yyyy')  contract_Date,  456  contract_id ,  12 days_past_due from dual union
select 1 client_id,      to_date('01-Aug-2015','dd-mon-yyyy')  contract_Date,  789  contract_id ,  99 days_past_due from dual union
-- add client 2 which shouldn't appear as first contract is past due
select 2 client_id,      to_date('01-Jan-2015','dd-mon-yyyy')  contract_Date,  444  contract_id ,  31 days_past_due from dual union
select 2 client_id,      to_date('01-May-2015','dd-mon-yyyy')  contract_Date,  555  contract_id ,  1 days_past_due from dual 
)
    SELECT * from (
        select client_id
             , contract_date
             , contract_id
             , days_past_due
             , row_number() over (partition by client_id order by contract_Date asc) contract_rank
             , lag(days_past_due) over (partition by client_id order by contract_date) prev_contract_past_due
        from thetable 
    ) 
    where contract_Rank = 2 and prev_contract_past_due is null