SELECT HOUR(t.transaction_date) hour,COUNT(t.id) transactions,SUM((tsl.unit_price_inc_tax-tsl.unit_price_before_discount)*tsl.quantity) profit,AVG((tsl.unit_price_inc_tax-tsl.unit_price_before_discount)/tsl.unit_price_before_discount)*100 margin FROM transactions t JOIN transaction_sell_lines tsl ON t.id=tsl.transaction_id WHERE t.type="sell" GROUP BY HOUR(t.transaction_date) ORDER BY profit DESC;