SELECT 
    bl.name as location_name,
    c.name as category_name,
    SUM(tsl.quantity) as total_quantity_sold,
    SUM(tsl.unit_price_inc_tax * tsl.quantity) as total_revenue,
    SUM((tsl.unit_price_inc_tax - tsl.unit_price_before_discount) * tsl.quantity) as total_margin,
    (SUM((tsl.unit_price_inc_tax - tsl.unit_price_before_discount) * tsl.quantity) / 
     SUM(tsl.unit_price_inc_tax * tsl.quantity) * 100) as margin_percentage
FROM business_locations bl
JOIN transactions t ON bl.id = t.location_id
JOIN transaction_sell_lines tsl ON t.id = tsl.transaction_id
JOIN products p ON tsl.product_id = p.id
JOIN categories c ON p.category_id = c.id
WHERE t.type = "sell" AND t.status = "final"
GROUP BY bl.id, bl.name, c.id, c.name
ORDER BY bl.name, margin_percentage DESC;