SELECT CASE WHEN TIMESTAMPDIFF(MINUTE,t.created_at,t.updated_at)<15 THEN "<15 min" WHEN TIMESTAMPDIFF(MINUTE,t.created_at,t.updated_at)<30 THEN "15-30 min" ELSE ">30 min" END duration,COUNT(t.id) transactions,AVG(basket.total_items) avg_items,AVG(t.final_total) avg_value FROM transactions t 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 1 ORDER BY avg_items DESC;