SELECT p.name product,v.name variation,COUNT(t.id) sales,SUM(tsl.quantity) units FROM products p JOIN variations v ON p.id=v.product_id JOIN transaction_sell_lines tsl ON v.id=tsl.variation_id JOIN transactions t ON tsl.transaction_id=t.id WHERE t.type="sell" GROUP BY p.id,v.id,p.name,v.name ORDER BY units DESC;