有一张记录人员信息的表
字段:pf_education:记录学历
字段:createtime:记录年份
字段:id
....
通过这张表按照年份查询不同学历的人数,如:
年度 本科人数 大专人数
2012 20 40
2013 26 42
2014 30 35
2015 40 20
SQL语句应该怎么写?
select count(1) pfEducation, sum(if(pf_education='学历值1',1,0)) pfEducation1 , sum(if(pf_education='学历值2',1,0)) pfEducation2 ,DATE_FORMAT(createtime,'%Y') createtime_Y from 表
GROUP BY DATE_FORMAT(createtime,'%Y')
order by createtime desc
select a.年度,a.本科人数,b.大专人数 from
(select createtime as '年度',count(pf_education) as '本科人数' from EmployeeInfo with(nolock) where pf_education = '本科' group by createtime,pf_education) as a
inner join
(select createtime as '年度',count(pf_education) as '大专人数' from EmployeeInfo with(nolock) where pf_education = '大专' group by createtime,pf_education) as b
on a.年度 = b.年度
order by a.年度
用这个试试
select
edu_year ,sum(t1) '大专',sum(t2) '本科'
from (
SELECT
DATE_FORMAT(t.createtime, '%Y') edu_year,
CASE WHEN t.pf_education ='大专' THEN count(t.id)
ELSE 0 END as t1 ,
CASE WHEN t.pf_education ='本科' THEN count(t.id)
ELSE 0 END as t2
FROM
表 t
GROUP BY
DATE_FORMAT(t.createtime, '%Y'),
t.pf_education ) tmp
GROUP BY edu_year