SUM统计使用CASE WHENsql
以下创建表结构,spa
create table test ( id int not null AUTO_INCREMENT, type int not null, value int not null, primary key (id) ); INSERT INTO test (type,value)VALUES(1,1),(2,2),(3,3),(4,4);
根据 根据type的值,value取不一样的值,而后sum,以下,code
select sum(case when type = 1 then value * 0.1 when type = 2 then value * 0.2 when type = 3 then value *0.3 when type = 4 then value * 0.4 else value end) as total from test ;
还好比说,以下的表结构,字符串
create table test1( id int not null AUTO_INCREMENT, name varchar(50) not null, birthday date not null, primary key (id) ) INSERT INTO test1(name,birthday) VALUES ('ll','1991-11-01'),('yy','2000-11-01'),('ss','2008-11-01'),('dd','2010-11-01');
以下查询,table
select name , case when birthday < '1995-11-01' then 'old' when birthday < '2000-11-01' then 'ok' when birthday < '2011-11-01' then 'young' else 'too native' end as hello from test1 ;
这就是case when 的基本用法。class
SQL中还有其余的判断语句,如 IF 和 IFNULL,以下表结构,test
create table test2 ( id int not null AUTO_INCREMENT, name varchar(50) not null, sex int not null, primary key (id) ); insert into test2 (name,sex) value('sdsd',1),('sdwe',2);
使用 IF 以下查询,date
select name , if(sex = 1, 'male','fmale') as sex from test2 ;
IF(expr1,expr2,expr3)select
若是 expr1 是TRUE (expr1 <> 0 and expr1 <> NULL),则 IF()的返回值为expr2; 不然返回值则为 expr3。IF() 的返回值为数字值或字符串值,具体状况视其所在语境而定。im
IFNULL(expr1,expr2)
假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1; 不然其返回值为 expr2。IFNULL()的返回值是数字或是字符串,具体状况取决于其所使用的语境。
========================END========================