SELECT cg.name segment,p.name product,COUNT(t.id) sales FROM customer_groups cg JOIN contacts c ON cg.id=c.customer_group_id JOIN transactions t ON c.id=t.contact_id JOIN transaction_sell_lines tsl ON t.id=tsl.transaction_id JOIN products p ON tsl.product_id=p.id WHERE t.type="sell" GROUP BY cg.id,cg.name,p.id,p.name ORDER BY sales DESC;