日期:2014-05-19  浏览次数:20446 次

怎样用sql求得每行行号
怎样用sql求得每行行号,不想用太复杂的方法。
如table(FA,FB)
DD,CC
GG,EE
AA,CC
希望得到
行号、FA,FB
1,AA,CC
2,DD,CC
3,GG,EE
简单地说就是在第一行前加一个如1,2,3....的数字

------解决方案--------------------
--如果FA是這樣的規律
Select (Select Count(FA) From TableName Where FA <= A.FA) As 行号 , * From TableName A
------解决方案--------------------
select
(select count(*) from tablename where Fa <a.Fa or fa=a.Fa and fb <=a.Fa) as 行号,
Fa,Fb
from tablename a
order by a.Fa,a.Fb

------解决方案--------------------
select identity(int,1,1) as iid,* into #t from table
select * from #t
drop table #t
------解决方案--------------------
alter table 表 add id int identity(1,1)
------解决方案--------------------
create table #table(name varchar(10))

insert into #table
select '张三 ' union all
select '李四 ' union all
select '大明 ' union all
select '小明 '

select identity(int,1,1) as iid,* into #t from #table
select * from #t
drop table #t
drop table #table
------解决方案--------------------
首先要指定一个排序吧.然后将记录取到临时表中,同时增加一个自增列,这个自增列就是行号.
只要有主键,有确定的排序,就可以实现.

------解决方案--------------------
Select Identity(int,1,1) as id,* Into #Table_Pqs From TableName Order By FA
Select * From #Table_Pqs
Drop Table #Table_Pqs


id FA FB
----------- ---------------------------------------------------------------- ----------------------------------------------------------------
1 AA CC
2 DD CC
3 GG EE

(所影响的行数为 3 行)
------解决方案--------------------
select 行号=(select count(1)+1 from Table where Fa <a.Fa),Fa,Fb from table a
------解决方案--------------------
select row_number() over (order by Fa) as 行号,FA,FB from tbl

------解决方案--------------------
qzxyd(只会种菜) ( ) 信誉:95 Blog 加为好友 2007-07-02 15:24:07 得分: 0


表中的任何字段都是没有关系的,我有可能是想得到某一排名的名次(如成绩排名),有可能只是想得到行号方便查看,但总会有一排序。看到大家都是用自增列加入到的临时表的方法,还有没有不需要临时表的方法呢。因为用临时表的话就不能直接嵌入程序里,只能用存储过程


------------------
--如果FA是這樣的規律,不用使用臨時表

Select (Select Count(FA) From TableName Where FA <= A.FA) As 行号 , * From TableName A

------解决方案--------------------
Select (Select Count(FA) From TableName Where FA <= A.FA) As 行号 , * From TableName A order by '行号 '