我在学习sqlserver, 下面这段代码应该如何改正:select a.FBusOrg, sum(case when b.FCarType='新车' then 1 else 0 end) as '新车笔数', sum(case when b.FCarType='二手车' then 1 else 0 end) as '二手车笔数', ( case when ('二手车笔数'=0 and '新车笔数'!=0) then 100 else '新车笔数'/'二手车笔数' end ) as '新车占比', ( case when sum(case when b.FCarType='新车' then 1 else 0 end)=0 then 100 else sum(case when b.FCarType='二手车' then 1 else 0 end)/sum(case when b.FCarType='新车' then 1 else 0 end) end ) as '二手车占比' from T_CL_Basic a left join T_CL_CarInfo b on a.FCustID=b.FCustID group by a.FBusOrg,b.FCarType
时间: 2024-01-24 09:03:07 浏览: 35
这段代码需要修改的地方如下:
1. 将字段别名用双引号括起来,而不是单引号。
2. 在计算“新车占比”时,需要先判断“二手车笔数”是否为0,不能直接使用字符串形式的“二手车笔数”。
3. 在计算“二手车占比”时,需要先判断“新车笔数”是否为0,不能直接使用计算结果作为分母。
修改后的代码如下:
```
select
a.FBusOrg,
sum(case when b.FCarType='新车' then 1 else 0 end) as "新车笔数",
sum(case when b.FCarType='二手车' then 1 else 0 end) as "二手车笔数",
(
case
when sum(case when b.FCarType='二手车' then 1 else 0 end)=0 and sum(case when b.FCarType='新车' then 1 else 0 end)!=0
then 100
else sum(case when b.FCarType='新车' then 1 else 0 end)/nullif(sum(case when b.FCarType='二手车' then 1 else 0 end), 0)
end
) as "新车占比",
(
case
when sum(case when b.FCarType='新车' then 1 else 0 end)=0
then 100
else sum(case when b.FCarType='二手车' then 1 else 0 end)/nullif(sum(case when b.FCarType='新车' then 1 else 0 end), 0)
end
) as "二手车占比"
from T_CL_Basic a
left join T_CL_CarInfo b on a.FCustID=b.FCustID
group by a.FBusOrg,b.FCarType
```