我有一个表,用于存储oracle中客户回复的状态。我必须计算客户的最后连续下降。
例如:
身份证明状态
-----------------------------
1.拒绝了
2.接受的
3.拒绝了
4.拒绝了
这将有计数= 2.
因为最后两个被拒绝了。
答案 0 :(得分:1)
注意:原始海报在“评论”中澄清,她需要一个不同的要求 - 在一个单独的答案中解决它。保持这一点,因为它显示了OP的更复杂问题的一种可能的解决方案。
假设您想要计算最近连续的“下降”(即使后面跟着“已接受” - 并且您希望允许多个客户 - 这是一种可能的解决方案。
输入表格(我称之为“t”):
SQL> select * from t;
CUSTOMER_ID DECISION_ID STATUS
----------- ----------- --------------------
10 1 Accepted
10 2 Declined
10 3 Declined
10 4 Accepted
10 5 Accepted
10 6 Declined
10 7 Declined
30 1 Declined
30 2 Accepted
30 3 Declined
30 4 Accepted
30 5 Declined
30 6 Declined
30 7 Declined
30 8 Accepted
30 9 Accepted
<强>查询:强>
with t1 as
(
select customer_id,
decision_id - row_number() over
(partition by customer_id order by decision_id) as idx
from t
where status = 'Declined'
),
t2 as (select customer_id, max(idx) as max_idx from t1 group by customer_id)
select t1.customer_id, count(1) as ct
from t1 join t2 on t1.customer_id = t2.customer_id
where t1.idx = t2.max_idx
group by t1.customer_id
order by t1.customer_id
/
查询输出:
CUSTOMER_ID CT
----------- ----------
10 2
30 3
答案 1 :(得分:0)
@Gurmeet - 然后问题就容易多了。这是解决它的一种方法。如果您需要customer_id排序的结果,请在最后添加order by customer_id
。如果客户从未进行过具有“已接受”状态的交易,则需要在CTE t2中定义d_A中的nvl。
输入:与我的其他答案相同。
查询 :(已修改以满足OP附加要求):
with t0 as (select customer_id, status, row_number() over
(partition by customer_id order by decision_id) rn from t),
t1 as (select customer_id, max(rn) as d_all from t0 group by customer_id),
t2 as (select customer_id, nvl(max(rn), 0) as d_A from t0
where status = 'Accept' group by customer_id)
select customer_id, d_all - d_A as ct from t1 natural join t2
/
<强>结果强>:
CUSTOMER_ID CT
----------- ----------
30 0
10 2
2 rows selected.