参考:
http://community.csdn.net/Expert/topic/3532/3532608.xml?temp=.2028009

解决方案 »

  1.   

    SQL语句难的,楼主可以用存储过程阿.
      

  2.   

    多谢bzszp(SongZip) ,yehanyu (愿生命化作那朵莲花) 
    学习!
      

  3.   

    如果数据量不大,可用group by AA,aa 分组的方法把结果存入内存,再用语言进行处理,便可输出你所想要的结果..
      

  4.   

    如果输出列:单位  AA  BB  CC  DD ... 相对确定:可以,
    否则考虑动态SQL,输出不确定列形式如:
    select c1, sum(c2) as s2, sum(c3) as s3, sum(c4) as s4....
    from (
    select b.b1 as c1, b.b3 as c2, 0 as c3, 0 as c4.... from b where b.b2='x1' union
    select b.b1 as c1, 0 as c2, b.b3 as c3, 0 as c4.... from b where b.b2='x2' union
    select b.b1 as c1, 0 as c2, 0 as c3, b.b3 as c4.... from b where b.b2='x3' union
    ....)
    group by c1sum 有时可以用 max 性能好些,但注意null和负数情况复杂的建议客户端脚本处理
      

  5.   

    也可以用decode处理列
    select b.b1 as c1,
    max(decode(b.b2,'x1',b.b3,null)), 
    max(decode(b.b2,'x2',b.b3,null)),
    max(decode(b.b2,'x3',b.b3,null)), 
    max(decode(b.b2,'x4',b.b3,null)),
    from b group by b.b1相比较性能可能比 union 慢一些。
      

  6.   

    http://community.csdn.net/Expert/topic/3539/3539241.xml?temp=.8740503
      

  7.   

    谢谢 yaozw_mountain(山林) 
    我先看下
      

  8.   

    使用decode或者case语句进行分组就好了^_^