当前位置: 代码迷 >> Sql Server >> SQL2000 男女信息统计有关问题
  详细解决方案

SQL2000 男女信息统计有关问题

热度:56   发布时间:2016-04-24 10:02:00.0
SQL2000 男女信息统计问题
select 
case when substring(col001,17,1)%2=0 then '女' else '男'end  as 性别,
count(case when substring(col001,17,1)%2=0 then '2' else '1'end) as 人数
   from sfz 
group by case when substring(col001,17,1)%2=0 then '女' else '男'end
union all
select '合计',count(case when substring(col001,17,1)%2=0 then '2' else '1'end)
from sfz
根据身份证号统计出男女的人数,结果如下,这是18位身份证号码的统计,当遇到中间有15位的身位证号就统计不对了,该怎么办?15倍最后一位是区分男女的,substring(col001,15,1)%2=0

性别   人数          
---- ----------- 
男    17
女    69
合计   86

(所影响的行数为 3 行)


------解决方案--------------------
CASE WHEN len(col001) = 18
     THEN case when substring(col001,17,1)%2=0 then '女' else '男' end  
     ELSE case when substring(col001,15,1)%2=0 then '女' else '男' end
END

------解决方案--------------------

SELECT 性别,count(1)as人数
FROM
(select(CASE WHEN len(col001) = 18
     THEN case when substring(col001,17,1)%2=0 then '女' else '男' end  
     ELSE case when substring(col001,15,1)%2=0 then '女' else '男' end
END)性别 from  sfz )A
GROUP BY 性别
UNION ALL
SELECT '合计',count(1) from sfz
  相关解决方案