← Practice

Order chain, gap ≤ 45 d: 'Уфа'

Level: SeniorTopic: Recursive CTEs200 XP

Instructions

Consider the orders of customers from the city 'Уфа', excluding cancelled ones (status = 'cancelled'). A customer's chain of repeat orders starts with their earliest order (by created_at; for ties, the one with the smaller id); the customer's next order in time joins the chain if it was created no later than 45 days (interval '45 days') after the previous order of the chain, otherwise the chain breaks and later orders are no longer part of it. For each customer with at least one such order, output customer_id, chain_orders (the number of orders in the chain) and chain_end (the date, type date, of the last order of the chain). Sort by customer_id ascending.

Hints

Each next one is more detailed and costs more

Log in to open hints

Query

Result

Click Run to see the query result, or Check to submit your solution.

Dataset schema

order_items.order_id (0…N) ↔ orders.id (1…1)order_items.product_id (0…N) ↔ products.id (1…1)orders.customer_id (0…N) ↔ customers.id (1…1)products.category_id (0…N) ↔ categories.id (1…1)categoriesPKidintegercustomersPKidintegerimport_logPKidintegerorder_itemsPKFKorder_idintegerPKFKproduct_idintegerordersPKidintegerFKcustomer_idintegerproductsPKidintegerFKcategory_idinteger
Exactly oneZero or oneZero or more
Table relationships
  • N:1Many-to-oneorder_items.order_id → orders.id
  • N:1Many-to-oneorder_items.product_id → products.id
  • N:1Many-to-oneorders.customer_id → customers.id
  • N:1Many-to-oneproducts.category_id → categories.id

Table data

PostgreSQL

Select a table in the diagram or list to view its rows.

Dataset schema