mssql sqlserver两条求和sql脚本相加的章程分享

发布时间:2019-09-29  栏目:NoSQL  评论:0 Comments

摘自:http://www.maomao365.com/?p=6612

转自:http://www.maomao365.com/?p=7205

manbet手机客户端3.0,摘要:
下文介绍sql server中,sql脚本幸免出现除零荒唐的法子分享

摘要:


下文分享两条sql求越剧本,再一次求和的措施分享

在各类事情种类开荒中,平时会遇上除零的一无所长,下文分享了二种管理措施:
方法1: case when end 

 /*
     例:
       下文已知两条sql求和脚本,现需对两张不同表的求和记录再次求和   
     */  
     ---对两条求和sql脚本求和的方法
      select sum(q) from 
      (
       select sum(qty)  as q from tableNameA where ...
       union all 
        select sum(qty)  as q from tableNameB where ...
       ) as table

     ---对多条求和sql脚本,再次求和的方法分享
     select sum(q) from 
      (
       select sum(qty)  as q from tableNameA where ...
       union all 
        select sum(qty)  as q from tableNameB where ...
         union all 
        select sum(qty)  as q from tableNameC where ...
        union all 
        select sum(qty)  as q from tableNameD where ...
       ...  
    ) as table
declare @a int ---分子
declare @b int ---分母
select  case  when @b=0 then NULL else @a/@b end  as [a除以b]

 


方法2:nullif
nullif(表达式A,表达式B)
—-假如表明式A不对等表明式B,则赶回表达式A
—-反之重临NULL 

 

declare @a int ---分子
declare @b int ---分母
select @a/nullif(@b,0) as [a除以b]

 

留下评论

网站地图xml地图