CASE用法



CASE 

          

 WHEN condition1 THEN returnvalue1 

         

  WHEN condition 2 THEN returnvalue2 

        

   WHEN condition 3 THEN returnvalue3 

         

  ELSE defaultreturnvalue 

END 


相当于if…else…else….


SELECT  FName, FWeight, 


(CASE 

    

      WHEN FWeight<40 THEN ‘瘦瘦'  

   

       WHEN FWeight>50 THEN ‘肥肥'  

     

     ELSE 'ok'  

        

  END) 

as isnormal 

FROM T_Person



create table bs

(

bsname char(20),

bsflag char(20),

bstime datetime

)


insert bs values('火箭','胜','2008-01-10')

insert bs values('火箭','负','2008-01-11')

insert bs values('火箭','胜','2008-01-10')

insert bs values('公牛','负','2008-01-10')

insert bs values('公牛','胜','2008-01-11')

insert bs values('公牛','负','2008-01-10')

select * from bs

select bsname,胜=sum(case when bsflag= '胜' then 1 else 0 end),

负=sum(case when bsflag='负' then 1 else 0 end)

 from bs group by bsname