Home >Database >Mysql Tutorial >select中case when的使用_MySQL

select中case when的使用_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-01 13:29:201571browse

bitsCN.com

select中case when的使用

 

select 与 case结合使用最大的好处有两点,一是在显示查询结果时可以灵活的组织格式,二是有效避免了多次对同一个表或几个表的访问。

例1:表 students(id, name ,birthday, sex, grade),要求按每个年级统计男生和女生的数量各是多少,统计结果的表头为,年级,男生数量,女生数量。如果不用select case when,为了将男女数量并列显示,统计起来非常麻烦,先确定年级信息,再根据年级取男生数和女生数,而且很容易出错。用select case when写法如下:

SELECT   grade, COUNT (CASE WHEN sex = 1 THEN 1      /*sex 1为男生,2位女生*/                                            ELSE NULL                                            END) 男生数,                            COUNT (CASE WHEN sex = 2 THEN 1                                            ELSE NULL                                            END) 女生数    FROM students GROUP BY grade

 

例2:

pat_visit.admission_date_time的日期格式为YYYY-MM-DD HH24:MI,求患者的年龄。create orreplaceview yw_viewas( selectcasewhen trunc(a.admission_date_time-b.date_of_birth)<30 and floor(a.admission_date_time-b.date_of_birth)>=1 then  round(a.admission_date_time-b.date_of_birth)||&#39;天&#39;  whenround(a.admission_date_time-b.date_of_birth)>30 andround(a.admission_date_time-b.date_of_birth)<365 then  round((a.admission_date_time-b.date_of_birth)/30)||&#39;月&#39; whenfloor(a.admission_date_time-b.date_of_birth)>&#39;365&#39;then  round((a.admission_date_time-b.date_of_birth)/365)||&#39;岁&#39;  whenceil(a.admission_date_time-b.date_of_birth)<=&#39;1&#39;then  round((a.admission_date_time-b.date_of_birth)*24*60)||&#39;分钟&#39;  end  as年龄,a.patient_idfrom pat_visit a,pat_master_index bwhere a.patient_id=b.patient_id);

 


bitsCN.com
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn