结果为: id name
5 名称1
6 名称2
7 名称3
. .
. .
. . 现在要Select出结果增加一列,使得执行后显示出来的数据如下所示(原表结构未更改,只是查出来的数据显示如下): id name new
5 名称1 1
6 名称2 2
7 名称3 3
. . 4
. . 5
. . .
. . .
5 名称1
6 名称2
7 名称3
. .
. .
. . 现在要Select出结果增加一列,使得执行后显示出来的数据如下所示(原表结构未更改,只是查出来的数据显示如下): id name new
5 名称1 1
6 名称2 2
7 名称3 3
. . 4
. . 5
. . .
. . .
select *,
new=(select count(*) from tb where id<=t.id)
from tb t
---2005
select *,
row_number()over(order by id)
from tb
select t.* , new = (select count(1) from tb where id < t.id) + 1 from tb t--sql 2005
select t.* , new = row_number() over(order by id) from tb t
select *,newid=(select count(1) from tb where id<a.id)+1 from tb a
--05
select *,newid=row_number() over(order by id) from tb
alter table tb
add new int identity
名称1
名称2
名称3
.
.
. 现在要Select出结果增加一列,使得执行后显示出来的数据如下所示(原表结构未更改,只是查出来的数据显示如下): name new
名称1 1
名称2 2
名称3 3
. 4
. 5
. .
. .
One Sample.0)结构和数据DECLARE @Var TABLE(id int,v_value varchar(32))INSERT INTO @Var
SELECT 1,'shen'
UNION ALL
SELECT 2,'liang'
UNION ALL
SELECT 4,'shine'
UNION ALL
SELECT 3,'sun'
UNION ALL
SELECT 5,'Liang'1)按照ID列升序加序号SELECT *,Seq = ROW_NUMBER()OVER(ORDER BY ID )FROM @Varid v_value Seq
----------- -------------------------------- --------------------
1 shen 1
2 liang 2
3 sun 3
4 shine 4
5 Liang 5(5 row(s) affected)2)按照@Var的记录顺序加序号SELECT *,Seq = ROW_NUMBER()OVER(ORDER BY GETDATE())FROM @Varid v_value Seq
----------- -------------------------------- --------------------
1 shen 1
2 liang 2
4 shine 3
3 sun 4
5 Liang 5
--sql 2000
select t.* , new = (select count(1) from tb where name < t.name) + 1 from tb t--sql 2005
select t.* , new = row_number() over(order by name) from tb t
--我的方法比较笨,要用到一个临时表
--测试数据
if object_id('your_table','U') is not null
drop table your_table;
gocreate table your_table(
name nvarchar(30)
);
goinsert into your_table
select '名称1' union all
select '名称2' union all
select '名称3' union all
select '名称4' union all
select '名称5' union all
select '名称6'
goif object_id('tempdb..#','U') is not null
drop table #;
goselect name,identity(int,1,1) as new
into #
from your_table select * from #;
--结果
/*
name new
名称1 1
名称2 2
名称3 3
名称4 4
名称5 5
名称6 6
*/
select *,
new=(select count(*) from tb where id<=t.id)
from tb t
---2005
select *,
row_number()over(order by id)
from tb