SELECT p.name,COUNT(DISTINCT CASE WHEN t.type="sell_return" THEN t.id END) returns,COUNT(DISTINCT CASE WHEN t.type="sell" THEN t.id END) sales,COUNT(DISTINCT CASE WHEN t.type="sell_return" THEN t.id END)*100.0/NULLIF(COUNT(DISTINCT CASE WHEN t.type="sell" THEN t.id END),0) return_rate FROM products p LEFT JOIN transaction_sell_lines tsl ON p.id=tsl.product_id LEFT JOIN transactions t ON tsl.transaction_id=t.id WHERE p.enable_stock=1 GROUP BY p.id,p.name ORDER BY return_rate DESC;