表:test1 班级编号(id) 姓名(name) 类别编号(lbbh) 年龄(age)
      如:001  张三  01 30
 001  李四  02 20
 001  王五  01 10
          002   李明 01 30
表:test2 类别编号(lbbh) 类别名称(lbmc)
         01             高级
         02             中级
现在要得到如下结果:
班级编号 高级 中级
001      40   20
002      30   0
这个SQL应该如何写

解决方案 »

  1.   

    班级编号 高级 中级 //test2具体的数据要作为表头吗?这用到交叉查询,在Delphi里不好实现。
    001      40   20
    002      30   0
    考虑重新设计一下表结构
      

  2.   

    test2具体的数据,可以不作表头,只要数据就行了
      

  3.   

    //以下语句在SQLServer测试通过
    select t1.id as 班级编号,ISNULL(CH,0) as 高级,ISNULL(CC,0) as 中级  from (select id,count(*) as CH from test1 where lbbh='01' group by id) as t1 left outer join (select id,count(*) as CC from test1 where lbbh='02' group by id) as t2 on (t1.id=t2.id)