SELECT c.name category,AVG((tsl.unit_price_inc_tax-tsl.unit_price_before_discount)/tsl.unit_price_before_discount)*100 avg_margin,STDDEV((tsl.unit_price_inc_tax-tsl.unit_price_before_discount)/tsl.unit_price_before_discount)*100 margin_volatility FROM categories c JOIN products p ON c.id=p.category_id 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 c.id,c.name ORDER BY margin_volatility;