什么是 case-when
case-when 是一种 sql 语句中的语法结构,结构如下:
case 字段名
when 值 then 字段名|值
...
else 字段名|值 end
case when 主要用于数据的 行列转换(把一列数据转换为多列)
前置条件:
-- 表结构如下:
create table demo2 ( country varchar(20),-- 国家 sex int,-- 性别,男=1,女=2 pop int-- 人口数量 );
-- 表数据如下:
insert into demo2 values('中国',1,340); insert into demo2 values('中国',2,240); insert into demo2 values('美国',1,45); insert into demo2 values('美国',2,55); insert into demo2 values('加拿大',1,40); insert into demo2 values('加拿大',2,65); insert into demo2 values('英国',1,34); insert into demo2 values('英国',2,60); commit;
编写查询实现如下效果:
效果1:
答案1:
select d.country , sum(case d.sex when 1 then d.pop else 0 end) as man , sum(case d.sex when 2 then d.pop else 0 end) as woman from demo2 d group by d.country ;
效果2:
答案2:
select case d.country when '中国' then '亚洲' when '英国' then '欧洲' else '美洲' end as 洲 , sum(d.pop) from demo2 d group by ( case d.country when '中国' then '亚洲' when '英国' then '欧洲' else '美洲' end ) ;
到此这篇关于mysql 中的case-when的文章就介绍到这了,更多相关mysql case-when内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论