SELECT c.type customer_type,p.name,COUNT(t.id) transactions,SUM(tsl.quantity) units FROM contacts c 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 c.type,p.id,p.name ORDER BY units DESC;