连续日期排名

时间:2013-06-27 15:22:25

标签: sql oracle rank row-number dense-rank

我需要获得连续的未付款金额:

with payments as
(
select '1' as ID, '20130331' as DateR, 'Not_paid' as Status from dual
union
select '1' as ID, '20130430' as DateR, 'Paid' as Status from dual
union
select '1' as ID, '20130531' as DateR, 'Not_paid' as Status from dual
union
select '2' as ID, '20130331' as DateR, 'Not_paid' as Status from dual
union
select '2' as ID, '20130430' as DateR, 'Not_paid' as Status from dual
union
select '3' as ID, '20130331' as DateR, 'Paid' as Status from dual
union
select '3' as ID, '20130430' as DateR, 'Paid' as Status from dual
union
select '3' as ID, '20130531' as DateR, 'Paid' as Status from dual
)

select ID, dater, status, dense_rank() over (partition by ID, status order by dater asc) rnk from payments

正如你所看到的那样,我从身份证2中获得了正确数量的未付款:他的第一笔未付款是在3月份,第二次是在4月份。 Id 3也可以,因为我以后会将他排除在外,但是对于id 1,它说第二次还款是在5月,而我想让它成为第一个,因为他在3月份未付款,但是在4月再次付款它应该从那里开始排名。一旦他支付了最后一笔款项,这个过程就会重新开始。

这个想法是在没有复杂查询的情况下保持简单。我只需要做密集排名,但只有当日期是连续的

我希望这个例子足够清楚。

编辑: 这是我从当前查询得到的:

ID    DATER      STATUS   RNK
1   20130331    Not_paid    1
1   20130531    Not_paid    2
1   20130430    Paid        1
2   20130331    Not_paid    1
2   20130430    Not_paid    2
3   20130331    Paid        1
3   20130430    Paid        2
3   20130531    Paid        3

我想得到的是:

 ID   DATER      STATUS   RNK
1   20130331    Not_paid    1
1   20130430    Paid        1
1   20130531    Not_Paid    1
2   20130331    Not_paid    1
2   20130430    Not_paid    2
3   20130331    Paid        1
3   20130430    Paid        2
3   20130531    Paid        3

这样,如果我想获得最大(等级)以检查用户当前有多少未付款,我得到该ID有1个未付款,ID 2有两个连续的未付款,而ID 3有0个未付款。这是因为在第四次连续付款时我必须考虑用户被搅动。

编辑:29/06/2013

有人在另一个论坛给了我一个完美的解决方案: https://forums.oracle.com/thread/2555552

1 个答案:

答案 0 :(得分:0)

这不是您问题的完整答案,但它可以为每个ID获取未付款的未付款数量。它为 Not_paid 状态指定值1,为付费状态指定-1。因此,我们可以按ID对查询进行分组,并对值列求和,以获得未付款项的数量。对于负数的金额,我们将其分配为零,因为它们没有未付款。

with payments as
(
select '1' as ID, '20130331' as DateR, 'Not_paid' as Status from dual
union
select '1' as ID, '20130430' as DateR, 'Paid' as Status from dual
union
select '1' as ID, '20130531' as DateR, 'Not_paid' as Status from dual
union
select '2' as ID, '20130331' as DateR, 'Not_paid' as Status from dual
union
select '2' as ID, '20130430' as DateR, 'Not_paid' as Status from dual
union
select '3' as ID, '20130331' as DateR, 'Paid' as Status from dual
union
select '3' as ID, '20130430' as DateR, 'Paid' as Status from dual
union
select '3' as ID, '20130531' as DateR, 'Paid' as Status from dual
)
SELECT id,
       DECODE(SIGN(SUM(value)), -1, 0, SUM(value))
  FROM (SELECT id,
               dater,
               status,
               DECODE(status, 'Paid', -1, 1) value
          FROM payments
       )
 GROUP BY id
 ORDER BY id;

现在,此查询适用于示例中的数据集,但可能不适用于更大的数据集。如果Not_paid状态的至少有相同数量的付费状态,它也将无效。例如,在 ID = 2 的示例中,如果帐户在5月份全额付款,则需要将2个付费条目加载到您的表中才能使我的解决方案正常运行。如果仅加载了1个付费条目,那么我的解决方案仍会显示此ID所需的未付款项。