SELECT p.name,COUNT(DISTINCT CASE WHEN t.type="sell_return" THEN t.id END) quality_issues,SUM(CASE WHEN t.type="sell_return" THEN tsl.quantity*tsl.unit_price_before_discount ELSE 0 END) quality_cost 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 quality_cost DESC;