SET @old_sql_mode = @@sql_mode;
SET @@sql_mode = '';

SELECT 
    pins.Manufacturer,
    v.VendorCode,
    ROUND(AVG(CASE
        WHEN v.PreviousCost != 0 THEN (
            (v.Cost - v.PreviousCost) / v.PreviousCost
        ) * 100
        ELSE 0
    END), 2) AS average_cost_change,
    COUNT(*) AS num_products,
    DATE(NOW()) AS date
FROM products.pins AS pins
JOIN products.vendor_map AS v
    ON v.PIN = pins.PIN
    AND v.VendorCode NOT IN ('VPW')
WHERE
    v.Cost != v.PreviousCost
    AND pins.Vertical IS NOT NULL
GROUP BY
    pins.Manufacturer,
    v.VendorCode
ORDER BY
    average_cost_change DESC;

SET @@sql_mode = @old_sql_mode;