Home > Database > Mysql Tutorial > MySQL按年龄段查询_MySQL

MySQL按年龄段查询_MySQL

WBOY
Release: 2016-06-01 13:17:32
Original
1966 people have browsed it

下面是项目中按照男女年龄段统计的核心sql代码:

                COUNT(tr.id)AS '体检总人数',		SUM(CASE WHEN s.sex=1 THEN 1 ELSE 0 END) AS '男体检总数',		SUM(CASE WHEN s.sex=0 THEN 1 ELSE 0 END) AS '女体检总数',				SUM(CASE WHEN s.sex=1 AND tr.age >=18 AND tr.age <=29 THEN 1 ELSE 0 END) AS '男18--29岁',		SUM(CASE WHEN s.sex=0 AND tr.age >=18 AND tr.age<=29 THEN 1 ELSE 0 END) AS '女18--29岁',				SUM(CASE WHEN s.sex=1 AND tr.age <=45 AND tr.age>=30 THEN 1 ELSE 0 END) AS '男30--39岁',		SUM(CASE WHEN s.sex=0 AND tr.age<=45  AND tr.age>=30  THEN 1 ELSE 0 END) AS '女30--39岁',				SUM(CASE WHEN s.sex=1 AND tr.age <=50 AND tr.age>=46 THEN 1 ELSE 0 END) AS  '男40--49岁',		SUM(CASE WHEN s.sex=0 AND tr.age<=50 AND tr.age>=46 THEN 1 ELSE 0 END) AS  '女40--49岁',				SUM(CASE WHEN s.sex=1 AND tr.age <=60 AND tr.age>50 THEN 1 ELSE 0 END) AS  '男50--59岁',		SUM(CASE WHEN s.sex=0 AND tr.age<=60 AND tr.age>50 THEN 1 ELSE 0 END) AS  '女50--59岁',				SUM(CASE WHEN s.sex=1 AND tr.age <=70 AND tr.age>60 THEN 1 ELSE 0 END) AS  '男60--69岁',		SUM(CASE WHEN s.sex=0 AND tr.age<=70 AND tr.age>60 THEN 1 ELSE 0 END) AS  '女60--69岁',				SUM(CASE WHEN s.sex=1 AND tr.age <=80 AND tr.age>70 THEN 1 ELSE 0 END) AS  '男70--79岁',		SUM(CASE WHEN s.sex=0 AND tr.age<=80 AND tr.age>70 THEN 1 ELSE 0 END) AS  '女70--79岁',				SUM(CASE WHEN s.sex=1 AND tr.age >80 THEN 1 ELSE 0 END) AS  '男80岁以上',		SUM(CASE WHEN s.sex=0 AND tr.age>80 THEN 1 ELSE 0 END) AS  '女80岁以上'
Copy after login

我拿其中一句解释一下

SUM(CASE WHEN s.sex=1 AND tr.age >=18 AND tr.age

先看sum的括号里面的部分

case when sex = 1 and age>=18 and age

它表示的含义是:如果性别为1(也就是男),并且年龄在18-29岁之间成立为1,不成立为0.

case和end 是一个关键字你可以理解为语句的开始和结束。

when相当于if做判断,then就是判断之后显示的结果。如果成立显示为1,不成立显示为0

sum就是将各个值相加。形如:1+1+0+1+0+1+1+0+1+1

项目最后统计的结果截图形如:



Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template