case when BB01.ABB008 = '02' then '1' else '0' end
时间: 2023-09-07 15:13:41 浏览: 44
这是一个 SQL 查询中的 CASE WHEN 语句,根据条件判断ABB008是否等于'02',如果是则返回'1',否则返回'0'。具体语法为:
```
CASE WHEN condition THEN result1 ELSE result2 END
```
其中,condition为判断条件,result1和result2为根据条件判断的结果。在这个例子中,condition为ABB008是否等于'02',result1为'1',result2为'0'。
相关问题
select nvl(sum(case when BB01.ABB008 = '02' then '1' else '0' end), 0) dbaj, nvl(sum(case when BB01.ABB029 = '0' AND BB01.ABB008 != '0' then '1' else '0' end), 0) blzaj, nvl(sum(case when BB01.ABB029 = '9' then '1' else '0' end), 0) ybaj, nvl(sum(case when 1 = 1 then '1' else '0' end), 0) ajtol from LABOR_LDJC.BB01 where BB01.AAE100 = '1';
这是一个 SQL 查询语句,查询 LABOR_LDJC.BB01 表中符合条件的数据,并对这些数据进行聚合统计。该查询语句的作用是统计满足特定条件的记录数量,并将结果按照指定的别名进行命名,别名分别为 dbaj、blzaj、ybaj 和 ajtol。
具体而言,该查询语句的含义如下:
- 查询 LABOR_LDJC.BB01 表中符合条件 BB01.AAE100 = '1' 的记录。
- 对满足条件的记录进行聚合统计,统计结果按照别名进行命名。
- 别名 dbaj 表示满足条件 BB01.ABB008 = '02' 的记录数量。
- 别名 blzaj 表示满足条件 BB01.ABB029 = '0' AND BB01.ABB008 != '0' 的记录数量。
- 别名 ybaj 表示满足条件 BB01.ABB029 = '9' 的记录数量。
- 别名 ajtol 表示查询结果的总记录数量。
其中,关键词 nvl 的作用是判断聚合结果是否为空,如果为空,则将其转换为 0。CASE WHEN 语句按照条件进行判断,并返回特定的结果。当条件成立时,返回 '1',否则返回 '0'。
我在学习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
这段代码需要修改的地方如下:
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
```