首页 > 开发 > 综合 > 正文

SQL数据排序 (转贴)

2024-07-21 02:12:20
字体:
来源:转载
供稿:网友

--测试表
create table test(f1 char(10), f2 char(10))

--插入数据
insert into test
select 'a' f1, '1' f2
union
select 'b' f1, '2' f2
union
select 'c' f1, '4' f2
union
select 'd' f1, '3' f2
union
select 'e' f1, '4' f2
union
select 'f' f1, '5' f2
union
select 'g' f1, '4' f2
union
select 'h' f1, '7' f2
union
select 'i' f1, '9' f2

---排名次
--方法1
select a.*,(select count(*) from test b where b.f2>a.f2)+1 as minci from test a order by minci
--方法2
select id = identity (int, 0, 1), f1, f2 into #t from test order by f2 desc
select a.f1, a.f2, a.id + 1 - cast(id - cc - minn as char(10)) as [名次]
from #t a, (select f2, cc, minn from (select f2, count(*) as cc, min(id) - count(*) as minn from #t group by f2) t) b
where a.f2 = b.f2
order by a.f2 desc

--删除表
drop table #t
drop table test

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表