SELECT p.name,tsl.unit_price_before_discount price,COUNT(t.id) sales,SUM(tsl.quantity) units,LAG(SUM(tsl.quantity)) OVER (PARTITION BY p.id ORDER BY tsl.unit_price_before_discount) prev_units FROM products p JOIN transaction_sell_lines tsl ON p.id=tsl.product_id JOIN transactions t ON tsl.transaction_id=t.id WHERE t.type="sell" GROUP BY p.id,p.name,tsl.unit_price_before_discount ORDER BY p.name,price;