SELECT p.name,COUNT(DISTINCT t.id) movement_count,SUM(CASE WHEN t.type IN ("purchase","sell","stock_transfer") THEN tsl.quantity ELSE 0 END) handled_quantity 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 movement_count DESC;