当前位置: 代码网 > it编程>数据库>Mysql > Mysql 中的case-when详解

Mysql 中的case-when详解

2024年07月05日 Mysql 我要评论
什么是 case-when case-when 是一种 sql 语句中的语法结构,结构如下: case 字段名 when 值 then 字段名|值 ... else 字段名|值

什么是 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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com