• The solution posted by Cadavre looks very complete.

    One possible change, when looking at the situation where there are fewer columns, in the SELECT clause, I'd probably use COALESCE instead of a CASE statement. But that's a pretty trivial change.

    "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