SELECT c.name category,COUNT(p.id) product_count,SUM(tsl.quantity*tsl.unit_price_before_discount) total_cost,AVG(tsl.unit_price_before_discount) avg_unit_cost 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 total_cost DESC;