您的位置:首页 > 其它

给查询增加一个序列

2010-01-07 21:18 155 查看
很多时候我们对查询的结果要增加一个序列,通常有用临时表和用自连接两种途径来实现。

用临时表:
select 序号= identity(int,1,1),* into #tmp from @t select * from #tmp ;
drop table #tmp

不用临时表:
select 序号=(select sum(1) from @t where and id<=a.id),*
from @t a order by a.id

稍稍复杂一点,假设表里面要根据不同的类型来加序列,可以这样:
select 序号=(select sum(1) from @t where type=a.type and id<=a.id),*
from @t a order by a.id

------测试代码-----------------------------
declare @t table (id int, type int)
insert @t
select 1 , 2  union
select 2 , 2 union
select 3 , 1 union
select 4 , 2 union
select 5,  3 union
select 6,  1 union
select 7,  3
select * from @t

select 序号=(select sum(1) from @t where type=a.type and  id<=a.id),*
from @t a order by  a.id


继续扩展一下。
select 序号=(select sum(1) from @t where type=a.type and id<=a.id),*
from @t a order by a.id
这个代码有一个情况:当最小id的两者id相同时(这里id假设不是主键,可以看作是成绩之类的),两个的序号都会变成2,或者说是并列第二。
我们通常喜欢将这种情况归为并列第一。这样我们可以将这个代码稍作修改。
------测试代码-----------------------------
declare @t table (id int, type int)
insert @t
select 1 , 2 union
select 2 , 2 union
select 3 , 1 union
select 4 , 2 union
select 5, 3 union
select 6, 1 union
select 7, 3 union all --------加入一行与上面一行同样id和type的数据
select 5, 3
select * from @t

select 序号=(select isnull(sum(1)+1,1) from @t where type=a.type and id<a.id),*
from @t a order by a.id


注意把比较的<=改成<之后,两个同样最小的id因为没有比它再小的id了所以sum(1)会变成null,所以这里要加个小小的处理。
再对上面的情况加一点点扩展。
如果我的比较方法是先比较id,如果id相同再比较另外一个字段来排序,那应该怎么修改上面的代码呢?
答案:
select 序号=(select isnull(sum(1)+1,1) from @t where type=a.type and (id<a.id or field<a.field) ),*
from @t a order by a.id
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐