SELECT tp.method payment_method,COUNT(t.id) transactions,SUM(t.final_total) total_sales,AVG((tsl.unit_price_inc_tax-tsl.unit_price_before_discount)/tsl.unit_price_before_discount)*100 avg_margin FROM transactions t JOIN transaction_payments tp ON t.id=tp.transaction_id JOIN transaction_sell_lines tsl ON t.id=tsl.transaction_id WHERE t.type="sell" GROUP BY tp.method ORDER BY avg_margin DESC;