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

在线求助 sql排序的问题
有一张表,其结构如下
sortNo int
finSelfCode varchar(25)
tFeeSum numeric(18,2)
corpName varchar(80)
finSelfCode的值存在上、下级的关系
其tFeeSum 值是上级之和  
有如下的数据
int finSelfCode tFeeSum corpName 
 1 00001 200 aa
 1 00002 2000 bb
 1 0000100001 50 cc
 1 0000100002 150 dd
 1 0000200001 500 ee
 1 0000200002 500 ff
 1 0000200003 1000 gg

怎么按tFeeSum排序同时 finSelfCode前五位相同的排一起,排在起的按tFeeSum和finSelfCode排序,并能显示排序的名次,其结果如下:
  int finSelfCode tFeeSum corpName 
  1 00002 2000 bb
  0000200003 1000 gg
  0000200001 500 ee
  0000200002 500 ff
  2 00001 200 aa
  0000100002 150 dd
  0000100001 50 cc

在线等待,请高手解答,急用!

------解决方案--------------------
SQL code
--> 测试数据: #T 
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (finSelfCode varchar(10),tFeeSum int,corpName varchar(2))
insert into #T
select '00001',200,'aa' union all
select '00002',2000,'bb' union all
select '0000100001',50,'cc' union all
select '0000100002',150,'dd' union all
select '0000200001',500,'ee' union all
select '0000200002',500,'ff' union all
select '0000200003',1000,'gg'
;
-->2005
with
T1 as
(
select *, max(tFeeSum)over(partition by left(finSelfCode,5)) as order_no from #T
),
T2 as
(
select *, strNo=case when len(finSelfCode)=5 then (select ltrim(count(distinct order_no)) from T1 where order_no>=t.order_no) else '' end from T1 t
)
select strNo, finSelfCode, tFeeSum, corpName from T2 order by order_no desc, tFeeSum desc
/*
strNo    finSelfCode tFeeSum  corpName
------------ ----------- ----------- --------
1      00002    2000    bb
      0000200003  1000    gg
      0000200001  500    ee
      0000200002  500    ff
2      00001    200    aa
      0000100002  150    dd
      0000100001  50      cc
*/

-->2000
if object_id('tempdb.dbo.#') is not null drop table #
select *, (select max(tFeeSum) from #T where left(finSelfCode,5)=left(t.finSelfCode,5)) as order_no into # from #T as t

select
strNo=case when len(finSelfCode)=5 then (select ltrim(count(distinct order_no)) from # where order_no>=t.order_no) else '' end,
finSelfCode,
tFeeSum,
corpName
from
# as t
order by
order_no desc, tFeeSum desc
/*
strNo    finSelfCode tFeeSum  corpName
------------ ----------- ----------- --------
1      00002    2000    bb
      0000200003  1000    gg
      0000200001  500    ee
      0000200002  500    ff
2      00001    200    aa
      0000100002  150    dd