'How can i use group by clause on case statement aliasing in tsql? [duplicate]

I have a case statement in my query with a aliasing and im trying to display it with group-by clause but i keep on getting the error "Invalid Column Name (case statement aliasing)"

Code

Select column 1,
       column 2,
       column 3,
       Case When .... then ...
            When .... then ...
            When .... then ... 
            else ... as X
From table1,
     table 2,
     table 3
where condition 1,
      condition 2,
      condition 3
group by column 1,
         column 2,
         X,
         column 3;

Output : Invalid Column name 'X'.



Solution 1:[1]

You need to include the whole case statement in the group by clause instead of using the alias. So

group by column 1,
         column 2,
       Case When .... then ...
            When .... then ...
            When .... then ... 
            else ... ,
         column 3;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A.Steer