1. 程式人生 > >Mysql:case when then end 的用法

Mysql:case when then end 的用法

ble 分享圖片 sel ota mat ima pri bubuko name

1、創建一張表,我們這表名為 t_score

drop table if exists t_score;
create table t_score
(
	id int primary key auto_increment,
	name varchar(20),
	course varchar(20),
	score double
) default charset = utf8;

2、添加若幹條數據

insert into `t_score`(name,course,score) values
    (‘王海‘, ‘語文‘, 86),
    (‘王海‘, ‘數學‘, 83),
    (‘王海‘, ‘英語‘, 93),
    (‘陶俊‘, ‘語文‘, 88),
    (‘陶俊‘, ‘數學‘, 84),
    (‘陶俊‘, ‘英語‘, 94),
    (‘劉可‘, ‘語文‘, 80),
    (‘劉可‘, ‘數學‘, 86),
    (‘劉可‘, ‘英語‘, 88),
    (‘李春‘, ‘語文‘, 89),
    (‘李春‘, ‘數學‘, 80),
    (‘李春‘, ‘英語‘, 87);

3、用case when then end 函數進行查詢

SELECT name,
max(CASE course WHEN ‘語文‘ THEN score ELSE 0 END ) Chinese,
max(CASE course WHEN ‘數學‘ THEN score ELSE 0 END ) math,
max(CASE course WHEN ‘英語‘ THEN score ELSE 0 END ) English,
sum(score) score
FROM t_score  
GROUP BY name
union
select ‘TOTAL‘,
sum(CASE course WHEN ‘語文‘ THEN score ELSE 0 END ),
sum(CASE course WHEN ‘數學‘ THEN score ELSE 0 END ),
sum(CASE course WHEN ‘英語‘ THEN score ELSE 0 END ),
sum(score) from t_score;

效果圖:

技術分享圖片

Mysql:case when then end 的用法