其实这个问题不难,不过今天碰上了,就记下来,权当做笔记,呵呵。
案例,做一个奥运排行榜,根据金,银,铜牌的奖牌数来排名,3种奖牌相同的时候排名并列。只有一个表,表结构如下:
create table t_medal
(
country varchar(50) primary key, -- 国家名
glod int, -- 金牌数
silver int, -- 银牌
bronze int -- 铜牌数
)
要求,列出奖牌排行榜(sql2005已经有这个语句,sql2000还没有)。
我是这样处理的,存储过程:
/*
获得奖牌排行榜
2008-07-31
*/
create procedure p_medal_list
as
set nocount on
-- 建立临时表,下面会用rownum来做排名
declare @tmptb table
(
rownum int identity(1,1), -- 做排名用
glod int,
silver int,
bronze int
)
-- 找出所有的奖牌情况,并按奖牌多少排名
insert into @tmptb(glod,silver,bronze)
select distinct glod,silver,bronze from t_medal
group by glod,silver,bronze
order by glod desc,silver desc,bronze desc
select a.country,a.glod,a.silver,a.bronze,b.rownum
from t_medal a inner join @tmptb b
on a.glod = b.glod and a.silver = b.silver and a.bronze = b.bronze
order by b.rownum asc
go
就这样,虽然没有sql2005那么简单,但是也不是很复杂。