\t\tASE产生排名除使用identity外另外的方式(转载)

ASE产生排名除使用identity外另外的方式

表定义如下:
create table x (a int null,b int null)
insert into x select 3,5
insert into x select 2,6
insert into x select 1,1
insert into x select 5,2
insert into x select 7,3
要求按照b字段给他们排名,得到类似于以下结果
a           b           seq
----------- ----------- -----
          1           1     1
          5           2     2
          7           3     3
          3           5     4
          2           6     5
        

1使用identity
select *,seq=identity(2) into #a from x order by 2
select *from #a

2使用自连接分组
select a.a,a.b,count(b.b) as seq from x a,x b where a.b >=b.b group by a.a,a.b order by 3


但如果使用第2种方法,在b数据有重复的情况下,得到的数据就不一样了。
insert into x select 8,5

1> select *,seq=identity(2) into #a from x order by 2
2> select *from #a
3> go
(6 rows affected)
a           b           seq
----------- ----------- -----
           1           1     1
           5           2     2
           7           3     3
           3           5     4
           8           5     5
           2           6     6

(6 rows affected)
1> select a.a,a.b,count(b.b) as seq from x a,x b where a.b >=b.b group by a.a,a.b order by 3
2> go
a           b           seq
----------- ----------- -----------
           1           1           1
           5           2           2
           7           3           3
           3           5           5
           8           5           5
           2           6           6

(6 rows affected)
b=5用地1个方法得到了4,5俩个排名,而2个方法大家都是5,而不是4
所以在排名字段如果存在重复值,就要看业务需求是否能够接受排名一致的情况
还有就是,这只是一个实现方法,如果数据量较大,性能恐怕成问题!

转载地址:http://blog.chinaunix.net/u/163/showart.php?id=96422

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值