最近做了一個統計分析,分析的内容是資料表裡面的根據身份證号來統計資料表中的男女人數
其實這個沒有什麼好說的,僅僅是最近用到了統計性别的
在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)這些函數和一定的邏輯關系