Question : GROUP BY Case Statements

Not necessarily a problem, but I have a question regarding using CASE statements in aggregating queries.

My querying is something similar to...

SELECT SUM(COLA), SUM(COLB),
CASE @MyVar
    WHEN 1 THEN 'XXX'
    WHEN 2 THEN 'XXX'
    WHEN 3 THEN 'XXX'
    WHEN 4 THEN 'XXX'
END AS COLC
FROM MyTable
GROUP BY
CASE @MyVar
    WHEN 1 THEN 'XXX'
    WHEN 2 THEN 'XXX'
    WHEN 3 THEN 'XXX'
    WHEN 4 THEN 'XXX'
END

...where 'XXX' are different values according to the case. Question is, will there be any performance impact in the above query because I repeating the entire CASE part of the query in the group by clause? Or would it be better to nest the first part of the query as a CTE and then do a group by on COL 3? Like this...

WITH MyCTE(COLA, COLB, COLC) AS
(
SELECT SUM(COLA), SUM(COLB),
CASE @MyVar
    WHEN 1 THEN 'XXX'
    WHEN 2 THEN 'XXX'
    WHEN 3 THEN 'XXX'
    WHEN 4 THEN 'XXX'
END
FROM MyTable
)
SELECT COLA, COLB, COLC FROM MyCTE GROUP BY COLC



Points will be given for best answer and any other pointers/tips/comments.

Answer : GROUP BY Case Statements

Done correctly, it should not make any difference, the optimizer is smart enough to reuse expressions.
But your CTE will not work that way - it still needs the group by in the CTE itself, and you have not gained anything.

The ad-hoc view would look like this:

select sum(ColA), sum(ColB), MyVar from
(SELECT ColA, ColB,
 CASE @MyVar
     WHEN 1 THEN 'XXX'
     WHEN 2 THEN 'XXX'
     WHEN 3 THEN 'XXX'
     WHEN 4 THEN 'XXX'
 END MyVar
 FROM MyTable) v
group by MyVar

The CTE is the same.
Random Solutions  
 
programming4us programming4us