I am trying to add a rank number for only delivered carts. I tried the below code but not getting the expected results.
Can we do this in a single query or we need to write a subquery for delivered carts & generate a rank. Please suggest here
Data:
customer_id | cart_id | cart_current_status | rank | delivered_rank |
---|---|---|---|---|
1 | 100 | DELIVERED | 1 | 1 |
1 | 110 | CANCELLED | 2 | NULL |
1 | 220 | DELIVERED | 3 | 2 |
Expected result: rank & delivered_rank Should be populated
Database: Amazon Redshift
select customer_id,cart_id,cart_current_status,
dense_rank() OVER (PARTITION BY customer_id
ORDER BY
cart_id ) AS cart_rank_asc,
(sum(case when cart_current_status = 'DELIVERED' then 1 else 0 end) over (partition by customer_id order by cart_id rows unbounded preceding)
) as delivered_cart_rank
from sales_details