您好,欢迎访问一九零五行业门户网

MySQL按年龄段查询_MySQL

下面是项目中按照男女年龄段统计的核心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 =18 and tr.age80 then 1 else 0 end) as '男80岁以上', sum(case when s.sex=0 and tr.age>80 then 1 else 0 end) as '女80岁以上'
我拿其中一句解释一下
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
项目最后统计的结果截图形如:

其它类似信息

推荐信息