最近做了一个统计分析,分析的内容是数据表里面的根据身份证号来统计数据表中的男女人数
其实这个没有什么好说的,仅仅是最近用到了统计性别的
在sql中也用到一些函数,自己认为应该记录下来吧
首先我们知道身份证号中存在着15位的和18位的,并且最后一位的奇偶表示着性别
所以我们在查询的时候首先要判断身份证号的位数,然后再判断最后一位的奇偶性
select sex,COUNT(sex) num from
(select idcard,
case
when length(idcard) = 15 and mod(substring(idcard,15,1),2) = 0 then '女'
when length(idcard) = 15 and mod(substring(idcard,15,1),2) = 1 then '男'
when length(idcard) = 18 and MOD(substring(idcard,17,1),2) = 0 then '女'
when length(idcard) = 18 and MOD(substring(idcard,17,1),2) = 1 then '男'
else null end sex
from table_name
where (LENGTH(idcard)=15 or LENGTH(idcard)=18)) a
group by sex
其实主要是因为在这个语句中用到的case..when...,substring(field,pos,len),mod(M,N)这些函数和一定的逻辑关系
所以会有点感觉复杂
希望对你有所帮助