SUM統計使用CASE WHEN

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========================

相關文章
相關標籤/搜索