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,SUM(CASE WHEN t.type="sell_return" THEN tsl.quantity ELSE 0 END) returned_units FROM products p JOIN transaction_sell_lines tsl ON p.id=tsl.product_id JOIN transactions t ON tsl.transaction_id=t.id GROUP BY p.id,p.name ORDER BY returns DESC;