Agreed with the group by: use the column name, not an integer.
If you have complex columns, I’ve seen an approach that works best is to use a subquery to ‘hide’ the comlex column generation: ie:
select a, b, c, count(*) n FROM (
select sum(*) as a, avg(case when x > 5 then 0 else 17) b, someComplex expression as c)
) Q
group by a,b,c