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
所以在排名字段如果存在重复值,就要看业务需求是否能够接受排名一致的情况
还有就是,这只是一个实现方法,如果数据量较大,性能恐怕成问题!
\t\tASE产生排名除使用identity外另外的方式(转载)
最新推荐文章于 2024-06-30 00:02:58 发布