case when 多个判断返回多个字段

2025-02-25 04:01:06
推荐回答(2个)
回答1:

select sum(case when end_km<5000 then 1 else 0 end) as [小于0.5万公里],
sum(case when end_km>=5000 and end_km<15000 then 1 else 0 end) as [0.5万到1.5万公里],
sum(case when end_km>=15000 and end_km<20000 then 1 else 0 end) as [1.5万到2万公里],
sum(case when end_km>=20000 and end_km<25000 then 1 else 0 end) as [2万到2.5万公里],
sum(case when end_km>=25000 and end_km<30000 then 1 else 0 end) as [2.5万到3万公里],
sum(case when end_km>=30000 then 1 else 0 end) as [2.5万到3万公里]
from 表名

as别名那地方,看你具体是什么数据库了,sqlserver或access的话就像我这么写,oracle的话,将[]换成一对双引号(英文写法滴),mysql的话将[]换成这个``(上边数字键1左边那个键)

回答2:

一个字段一个字段的判断
就是a和b都不等于0返回的话
select table.*,
(case when a<>0 and b<>0 then c%a
else 0 end) as e,
(case when a<>0 and b<>0 then (c%a)%b
else 0 end) as d
from table where ……

如果是其他情况,再添加case when条件