今天查询数据库时遇到一个问题,一个表中存了三种不同状态的的记录,即仓库日志表里存了 领出,报废,归还三个状态的字段,而我需要做的操作是统计出一个人的领用总数量,报废总数量,和归还总数量,自己用了很多种方法,但都行不通,最后还是大神提供了case when语句才得以解决,所以写下这篇日志得以记录以便不时之需;
case when 听起名字就知道,应该和switch 语句差不多;所以他的一般格式为:
case
when 列名= 条件值1 then 选择项1
when 列名=条件值2 then 选项2.......
else 默认值 end
你可以在 then 后面写任何值,当然你也可以用表中的字段 作为选项,我写的是多重 查询语句;
select UID,UNAME,sum(LingChuNum)as LCNUM,sum(BaoFeiNum)as BFNUM,sum(GuiHuanNum)as GHNUM FROM
(
select uid ,uname,
case when Type=1 then OutNum else 0 end as LingchuNum,
case when Type=2 then OutNum else 0 end as BaoFeiNum,
case when Type=3 then OutNum else 0 end as GuiHuanNum,
from WareHouseLogList where UID=1 and Wcode=‘1001’
)t group by(UID,UNAME )