SELECT p.name,AVG(basket.total_items) avg_basket_size FROM products p JOIN transaction_sell_lines tsl ON p.id=tsl.product_id JOIN transactions t ON tsl.transaction_id=t.id JOIN (SELECT transaction_id,SUM(quantity) total_items FROM transaction_sell_lines GROUP BY transaction_id) basket ON t.id=basket.transaction_id WHERE t.type="sell" GROUP BY p.id,p.name ORDER BY avg_basket_size DESC;