• CASE statement in the GROUP BY clause is also going to lead to some pretty poor choices by the optimizer.

    If you have two different sets of logic, rather than try to cram them into a single procedure, create two procedures and call them from a wrapper procedure based on the needs of the separated logic. That's going to give the optimizer a better chance at arriving at a good plan.

    Plus everything already pointed out.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning