select * from table1
a1(病房)        a2(人数)      a3(1代表爱滋病、1代表感冒、3代表骨折)
1001            5            1
1001            6            2
1001            7            3
有没有办法实现输出下面的格式:病房     爱滋病人数    感冒人数    骨折人数
1001       5             6            7也就是三行汇总成一行?、、

解决方案 »

  1.   

    a1(病房)        a2(人数)      a3(1代表爱滋病、2代表感冒、3代表骨折)交叉表语句的实现:
    --用于:交叉表的列数是确定的
    select a1,sum(case a3 when 1 then a2 else 0 end) as '爱滋病',
              sum(case a3 when 2 then a2 else 0 end) as '感冒',
                sum(case a3 when 3 then a2 else 0 end) as '骨折' 
    from table1 
    group by a1
      

  2.   

    好像有点问题,老是提示未找到 from 关键字
    把''号去掉后 也有问题,
    else后面一定是0吗?谢谢回复
      

  3.   

    你检查一下,应该没问题
    ------------------------------
    create table test
    (a1 char(4),
     a2 int,
     a3 char(1))insert test(a1,a2,a3)
    select '1001',5,'1' union all
    select '1001',6,'2' union all
    select '1001',7,'3' union all
    select '1002',9,'2' select * from test
    select a1,sum(case a3 when 1 then a2 else 0 end) as '爱滋病',
              sum(case a3 when 2 then a2 else 0 end) as '感冒',
              sum(case a3 when 3 then a2 else 0 end) as '骨折' 
    from test
    group by a1drop table test
      

  4.   

    上面的没有问题吧,是不是FROM 写成了FORM,呵呵
    else后面 0的意思是指(1代表爱滋病、1代表感冒、3代表骨折)条件之外
    的情况
      

  5.   

    但是如果表里的数据多了的话好像输出结果是人数的和,比如
    select * from table1
    a1(病房)        a2(人数)      a3(1代表爱滋病、1代表感冒、3代表骨折)
    1001            5            1
    1001            6            2
    1001            7            3
    1002            4            1
    1002            5            2
    1002            8            3那么好像是求和不用SUM可以吗?用别的什么呢?
      

  6.   

    select  a.a1,a.a2,b.a2 ,c.a2 from table1 a,table1 b ,table1 c where a.a1=b.a1 and c.a1=a.a1 and a.a3 ='1' and b.a3='2' and c.a3='3'ok ,please check above !please thank me !!!!!!!
      

  7.   

    谢谢各位高手的回复
    不过小弟还是个菜鸟,无赖单位其他人比我还菜,被迫的。
    我把这个重新发个详细标题,yizhi和飘飘再看看呀