sql查询数据排名的方法

2019-04-20 08:56:14来源:爱站网 阅读 ()

新老客户大回馈,云服务器低至5折

? ? ? 有时候我们在数据库的操作中需要查询某个范围的数据排行,那么应该怎么办呢?下面是爱站小编为大家总结出sql查询数据排名的方法,感兴趣的朋友们一起看看吧。

1/准备测试数据

---------------------------------------------------------------------------------
create table t1(
c1 integer,
c2 integer,
c3 integer
);

insert into t1 values(1,2,3)

insert into t1 values(1,8,4)
insert into t1 values(1,4,4)

insert into t1 values(1,4,5)

insert into t1 values(1,5,5)

insert into t1 values(2,2,3)

insert into t1 values(2,8,4)
insert into t1 values(2,4,4)

insert into t1 values(2,4,5)

insert into t1 values(2,5,5)

2/查看排名

---------------------------------------------------------------------------------

A/单记录排名

select c1,c3,
(select count( c3)+1 from t1 a where a.c3>b.c3
and a.c1=b.c1 and a.c1 =1
) order_num
from t1 b
where? c1 =1
order by c1,c3

c1????????? c3????????? order_num?????????????
----------- ----------- ----------------------
1?????????? 3?????????? 5?????????????????????
1?????????? 4?????????? 3?????????????????????
1?????????? 4?????????? 3?????????????????????
1?????????? 5?????????? 1?????????????????????
1?????????? 5?????????? 1?????
B/多记录排名

select c1,c2,c3,
(select count( c3)+1 from t1 a where a.c3>b.c3
and a.c1=b.c1
) order_num
from t1 b
order by c1,c3


c1????????? c2????????? c3????????? order_num?????????????
----------- ----------- ----------- ----------------------
1?????????? 2?????????? 3?????????? 5?????????????????????
1?????????? 8?????????? 4?????????? 3?????????????????????
1?????????? 4?????????? 4?????????? 3?????????????????????
1?????????? 4?????????? 5?????????? 1?????????????????????
1?????????? 5?????????? 5?????????? 1?????????????????????
2?????????? 2?????????? 3?????????? 5?????????????????????
2?????????? 8?????????? 4?????????? 3?????????????????????
2?????????? 4?????????? 4?????????? 3?????????????????????
2?????????? 4?????????? 5?????????? 1?????????????????????
2?????????? 5?????????? 5?????????? 1??

? ? ? 以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持爱站技术频道!


原文链接:https://js.aizhan.com/data/mssql/5597.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:将Access数据库移植到SQL Server 7.0

下一篇:SQL的常用语句