SUM统计使用CASE WHEN

SUM统计使用CASE WHEN

如下建立表结构,

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,如下,

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');

如下查询,

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 的基本用法。

SQL中还有其他的判断语句,如 IF 和 IFNULL,如下表结构,

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 如下查询,

select name , if(sex = 1, 'male','fmale') as sex from test2 ;

IF(expr1,expr2,expr3)

如果 expr1 是TRUE (expr1 <> 0 and expr1 <> NULL),则 IF()的返回值为expr2; 否则返回值则为 expr3。IF() 的返回值为数字值或字符串值,具体情况视其所在语境而定。

IFNULL(expr1,expr2)

假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1; 否则其返回值为 expr2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境。

========================END========================

你可能感兴趣的:(SUM统计使用CASE WHEN)