• This can still be optimized (I'm out of time here). But this should be an enormous improvement.

    WITH CTE AS

    (

    SELECT Usr,

    CASE WHEN val1=1 THEN 1 END AS val1,

    CASE WHEN val1=3 THEN val2+1 END AS val2,

    CASE WHEN val1=0 THEN val3 END AS val3

    FROM TestExecPlans

    )

    INSERT INTO DestTable

    SELECT *,

    (SELECT MIN(mv)

    FROM (VALUES (val1), (val2), (val3)) AS t(mv)) AS MinSimilarity,

    (SELECT MAX(mv)

    FROM (VALUES (val1), (val2), (val3)) AS t(mv)) AS MaxSimilarity,

    MAX(val1) OVER (PARTITION BY Usr) AS maxval

    FROM CTE;

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001