有这样一个数据表姓名  年龄  出生年 年级 系别 专业
..     ..      ..   ..   ..   ..如何用sql语句生成这样一个查询结果来统计人数    年龄  18   19   20
系别生物           300英语30代表生物专业19岁的有20人,如何实现?

解决方案 »

  1.   

    declare @sql varchar(8000)
    set @sql = 'select 系别 '
    select @sql = @sql + ',sum(case 年龄 when '''+年龄+''' 
    then 1 else 0 end) as '''+年龄+''''
    from (select distinct 年龄 from test) as a
    select @sql = @SQL + ' from test group by 系别'
    exec(@sql)
    go
    差不多是这样
      

  2.   

    if object_id('tbTest') is not null
    drop table tbTest
    GO
    create table tbTest (姓名 varchar(10),年龄 int, 系别 varchar(10))
    insert tbTest
    select '张三',21,'英语' union all
    select '李四',22,'英语' union all
    select '王五',22,'生物' union all
    select '赵六',22,'生物' union all
    select '马七',21,'生物' union all
    select '冯八',23,'化学' ----查询
    declare @sql varchar(8000)
    set @sql = 'select 系别' 
    select @sql = @sql + ',[' + rtrim(年龄) + ']=sum(case 年龄 when ' + rtrim(年龄) + ' then 1 else 0 end)'
    from tbTest group by 年龄
    EXEC(@sql + ' from tbTest group by 系别')drop table tbTest
    /*结果
    系别         21          22          23          
    ---------- ----------- ----------- ----------- 
    化学         0           0           1
    生物         1           2           0
    英语         1           1           0
    */