现在有一张表,有BirthYear(出生年)和Degree(学位),(dep)系别三个字段,需要统计在一定出生年间隔内的符合某个学位的人数,比如:
1900-1902出生人员统计结果 
    博士 硕士 学士 总计 
政治科学系 0 0 0 0 
行政管理系 0 0 0 0 1903-1905出生人员统计结果 
    博士 硕士 学士 总计 
政治科学系 0 0 0 0 
行政管理系 0 0 0 0 1906-1908出生人员统计结果 
    博士 硕士 学士 总计 
政治科学系 0 0 0 0 
行政管理系 0 0 0 0 请问怎样按时间间隔分组,sql语句该怎样写?谢谢

解决方案 »

  1.   

    http://topic.csdn.net/u/20071214/10/87743826-2644-479a-b144-731c4b29b07e.html将记录中的日期值按这个贴子里的方式进行分组聚合.
    再将聚合结果与原表连表即可得出.
      

  2.   

    select dep , 时间 = '1900-1902',
      sum(case when year(BirthYear) 1900 and 1902 and 学位 = '博士' then 1 end) '博士',
      sum(case when year(BirthYear) 1900 and 1902 and 学位 = '硕士' then 1 end) '硕士',
      sum(case when year(BirthYear) 1900 and 1902 and 学位 = '学士' then 1 end) '学士',
      sum(case when year(BirthYear) 1900 and 1902 then 1 end) '总计'
    from tb group by dep
    union all
    select dep , 时间 = '1903-1905',
      sum(case when year(BirthYear) 1903 and 1905 and 学位 = '博士' then 1 end) '博士',
      sum(case when year(BirthYear) 1903 and 1905 and 学位 = '硕士' then 1 end) '硕士',
      sum(case when year(BirthYear) 1903 and 1905 and 学位 = '学士' then 1 end) '学士',
      sum(case when year(BirthYear) 1903 and 1905 then 1 end) '总计'
    from tb group by dep
    union all
    select dep , 时间 = '1906-1908',
      sum(case when year(BirthYear) 1906 and 1908 and 学位 = '博士' then 1 end) '博士',
      sum(case when year(BirthYear) 1906 and 1908 and 学位 = '硕士' then 1 end) '硕士',
      sum(case when year(BirthYear) 1906 and 1908 and 学位 = '学士' then 1 end) '学士',
      sum(case when year(BirthYear) 1906 and 1908 then 1 end) '总计'
    from tb group by dep