日期:2014-05-18  浏览次数:20505 次

查询简单的问题!
有如下列:

  班级代码(dm)         分数(score)
      1                                 10
      2                                 30
      3                               -20
      4                               -30
      5                                 40
      1                                 60


现在我实现如下查询结果:
班级代码     加奖       加奖合计       班级代码       扣奖       扣奖合计
  1                   10             20                   1                   -10           -10
  1                   10                                   2                   -20           -20
根本没有一一对应!应该显示的是:
班级代码     加奖       加奖合计       班级代码       扣奖       扣奖合计
  1                   10             20                   1                   -10           -10
  1                   10                                 null             null         null
  2                   30             30                 2                     -20           -20


也就是说将单独的那个分数列,用两列显示出来分别显示的> 0的一列和 <0的一列。完了算出来每个班级代码分数的合计也单独用一列显示出来。(如上图的结果)

------解决方案--------------------
--是这样么?
create table tb(dm int,score int)
insert tb
select 1,10
union select 2,30
union select 3,-20
union select 4,-30
union select 5,40
union select 1,60


select 班级代码=case when score> 0 then dm else null end,
加奖=case when score> 0 then score else null end,
加奖合计=(select sum(score) from tb where t.dm=dm AND score> 0 ),
班级代码=case when score <0 then dm else null end,
加奖=case when score <0 then score else null end,
加奖合计=(select sum(score) from tb where t.dm=dm AND score <0 )
from tb t


drop table tb


/*
班级代码 加奖 加奖合计 班级代码 加奖