id num1 num2 result
1 2 3 (3-2)/2
2 1 2 (2-1)/1
现在要求在result 字段的 计算列所得规范 的公式写上 (num2-num1)/num1
num1 的值可能为0怎么处理。能不能 加case when 那么判断 ,请高手指点
1 2 3 (3-2)/2
2 1 2 (2-1)/1
现在要求在result 字段的 计算列所得规范 的公式写上 (num2-num1)/num1
num1 的值可能为0怎么处理。能不能 加case when 那么判断 ,请高手指点
---------------------------------
-- Author: htl258(Tony)
-- Date : 2009-07-23 14:38:38
---------------------------------
--> 生成测试数据表:tbIf not object_id('[tb]') is null
Drop table [tb]
Go
Create table [tb]([id] int,[num1] int,[num2] int)
Insert tb
Select 1,2,3 union all
Select 2,0,2
Go
--Select * from tb-->SQL查询如下:
select *,result=case [num1] when 0 then 0 else ([num2]-[num1])/[num1] end
from tb
/*
id num1 num2 result
----------- ----------- ----------- -----------
1 2 3 0
2 0 2 0(2 行受影响)
*/
create table tt1(id int, num1 int, num2 int, result as case when (num2-num1)/num1=0 then 你要的值 else (num2-num1)/num1 end )
Drop table [tb]
Go
Create table [tb]([id] int,[num1] int,[num2] int)
Insert tb
Select 1,2,3 union all
Select 2,0,2
Go
select * ,
result=case when rtrim([num1])='0' then '分母不能为0'
else rtrim(cast(([num2]-[num1])*1.0/[num1]as decimal(18,1))) end
from tb
id num1 num2 result
----------- ----------- ----------- -----------------------------------------
1 2 3 0.5
2 0 2 分母不能为0(2 行受影响)