日期:2014-05-18 浏览次数:20518 次
--> 测试数据: #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