在某些需求情况下,我们需要在查询表数据的结果中增加一个自增序列来直观表现当前数据的排列情况或者是排名情况,这样结果集的排列或者排名就比较明显,那在各种数据库中是如何来实现的呢?下面针对几种主流的数据库来举例看下。
一、SQL
Server数据库
对于SQL Server数据库,在查询结果集中增加自增序列,因版本不同而有所不同。
1、SQL Server2000 SQL查询结果中自增序列
select
identity(int,1,1)
uid,user_name,sum(score)score
into
#tmp
from
t_user_info
group
by user_name
order
by sum(score) desc
select
*
from
#tmp
2、SQL Server2005及以上
SQL查询结果中自增序列
a、使用over函数排序
select
row_number() over (order by sum(score)
desc) uid,user_name,sum(score)score
from
t_user_info
group
by user_name
b、over函数中不做排序处理
select
row_number() over (order by getdate())
uid,user_name,sum(score)score
from
t_user_info
group
by user_name
order
by sum(score) desc
注意
:SQL
Server2005及以上版本中还有其他一些排名函数,如:rank(),dense_rank(),ntile()等,详细用户这里不再叙述。
二、Mysql
SQL查询结果中自增序列
1、先初始化一个变量,在查询时递加
SET
@i=0;
SELECT
@i:=@i+1 AS id,NAME,COUNT(NAME)
name_num
FROM
persons
GROUP
BY NAME
ORDER
BY COUNT(NAME) DESC
2、初始变量作为一个对象进行递加
SELECT
@i:=@i+1 AS id,a.name,COUNT(a.name)
name_num
FROM
persons a,(SELECT @i:=0) AS b
GROUP
BY a.name
ORDER
BY COUNT(a.name) DESC
3、表内数量关联,在查询时自增排序
SELECT
(SELECT COUNT(*)+1 FROM
(SELECT uname,COUNT(uage)uage FROM t_allcol_repet GROUP BY
uage)a
WHERE uage>b.uage) AS
paiming,b.uname
FROM
(SELECT uname,COUNT(uage)uage
FROM
t_allcol_repet
GROUP
BY uage
ORDER
BY b.uage DESC
注意
:一般常用的为方法1和2,使用第三中方法,需要表中存在一定的数量比较关系。
三、Oracle
SQL查询结果中自增序列
1、利用row_number() 函数生成自增列
select
row_number() over()
uid,user_name,sum(score)score
from
t_user_info
group
by user_name
order
by sum(score) desc
2、利用rownum 函数生成自增列
select
rownum,a.* from (select
uid,user_name,sum(score)score
from
t_user_info
group
by user_name
order
by sum(score) desc
3、利用序列,在查询是生成自增列
a、创建序列seq_tmp
:
create
sequence seq_tmp
maxvalue 100000
minvalue 1
start with 1
increment by 1
cache 10
b、利用序列,在查询时生成自增列
select
seq_tmp.nextval
as id,user_name,sum(score)score
from
t_user_info
group
by user_name
order
by sum(score) desc
新浪简介
|
About Sina
|
广告服务
|
联系我们
|
招聘信息
|
网站律师
|
SINA English
|
产品答疑