May 29, 2025

Find maximun difference in the order for the same customer SQL

 WITH CustomerData AS(


SELECT      customer_id,

            oz.order_id, 

            product_id,

            SUM(quantity)  AS purchase_quantity, 

            SUM(quantity) - LAG(SUM(quantity)) OVER(PARTITION BY customer_id,product_id ORDER BY order_id) quantity_diff

FROM        orders_amz oz

INNER JOIN  orderdetails o ON o.order_id=oz.order_id

GROUP BY customer_id,oz.order_id, product_id)


SELECT      c.customer_id, 

            p.product_id, 

            product_name

FROM        products_amz p 

INNER JOIN  CustomerData c on c.product_id=p.product_id

ORDER BY    quantity_diff DESC

LIMIT 1


 

No comments: