日期:2014-05-19  浏览次数:20481 次

排名的问题 求一SQL

create   table   a
(sname   int,
  smonth   int,
  score   int)

insert   into   a   values   (   1,7,80)
insert   into   a   values   (   1,8,40)
insert   into   a   values   (   1,9,80)
insert   into   a   values   (   2,7,50)
insert   into   a   values   (   2,8,40)
insert   into   a   values   (   2,9,60)
insert   into   a   values   (   3,7,50)
insert   into   a   values   (   3,8,80)
insert   into   a   values   (   3,9,60)
select   sname,sum(score*(case   when   smonth=7   then   1   else   0   end))   [7月],
sum(score*(case   when   smonth=8   then   1   else   0   end))   [8月],sum(score*(case   when   smonth=9   then   1   else   0   end))   [9月],
sum(score)   总分,(select   count(*)+1   from   (select   'a '   a   from   a   group   by   sname   having   sum(score)>   (select   sum(score)   s   from   a   i   where   i.sname=o.sname)   )t   )       排名
from   a   o  
group   by   o.sname

    看的人   在查询分析器看下     是正确的
  这是一个高手写的一个排序,我的要求跟这有点不一样   ,我表中的a   需要有参数输入的         其中的table     a   需要查询下   ,也就是select   sum(score),......   from       realtable   where   month   in   (4,5,6)   group   by     ....   需要输入参数动态查询某个季度的排名,各位高手可以以   4   ,5   ,6   月为例子     写个SQL
     

另外     以上的这句   select   sum(score)   s   from   a   i   where   i.sname=o.sname)     实在看不懂

谢谢


------解决方案--------------------
create table a
(sname int,
smonth int,
score int)

insert into a values ( 1,7,80)
insert into a values ( 1,8,40)
insert into a values ( 1,9,80)
insert into a values ( 2,7,50)
insert into a values ( 2,8,40)
insert into a values ( 2,9,60)
insert into a values ( 3,7,50)
insert into a values ( 3,8,80)
insert into a values ( 3,9,60)

--SQL
select sname,
[7月]=sum(case when smonth=7 then score else 0 end),
[8月]=sum(case when smonth=8 then score else 0 end),
[9月]=sum(case when smonth=9 then score else 0 end),
[总分]=sum(score),
[排名]=( select count(*)+1 from(
select col=1 from a group by sname having sum(score)> sum(tmpA.score)
) tmp
)
from a tmpA
group by sname

--result
sname 7月 8月 9月 总分 排名
----------- ----------- ----------- ----------- ----------- -----------
1 80 40 80 200 1
2 50 40 60 150 3
3 50 80 60 190 2

(3 row(s) affected)