SQL查询group by 中的case when 不能加 as 字段别名 ,不然会报错
为此有两种解决办法:
1. group by 写法直接省略分组字段,用数字代替,1代表year,2代表name,有几个分组字段就写到几
select
year
,name
, case when month <=6 then 'h1'
when month >6 then 'h2'
else null end as 'half_year'
,sum(score)
from table
group by 1,2,3
2. group by case when 写到end 就可以,不加as
select
year
,name
, case when month <=6 then 'h1'
when month >6 then 'h2'
else null end as 'half_year'
,sum(score)
from table
group by
year
,name
, case when month <=6 then 'h1'
when month >6 then 'h2'
else null end -- 注意这里不需要加as 字段别名