求一条sql语句

zengzhimin1980 2009-09-24 04:12:13
如现在有表

table1
===========================
name num
a 10
b 20
c 3
d 8
.........


我想在select语句中加入一列ID,ID的值是按行数自增的
如 select name,num,ID from table1

怎样写?
...全文
48 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wen1512 2009-09-24
  • 打赏
  • 举报
回复
select name,num,row_number() over(order by name) as id from table1
soft_wsx 2009-09-24
  • 打赏
  • 举报
回复
if OBJECT_ID('tb') is not null drop table tb
go
create table tb(name nvarchar(10),num int)
insert tb
select
'a', 10 union all select
'b' , 20 union all select
'c' , 3 union all select
'd' , 8
--2005
select *,sn=ROW_NUMBER() over(order by num) from tb
--2000
select *,sn=(select COUNT(1) from tb where num>=a.num) from tb a
order by sn
/*
name num sn
b 20 1
a 10 2
d 8 3
c 3 4*/
jiangshun 2009-09-24
  • 打赏
  • 举报
回复

--> 测试数据:#TB
--> 我的淘宝:http://shop36766744.taobao.com/
if object_id('tempdb.dbo.TB') is not null drop table #TB
create table TB([name] varchar(1),[num] int)
insert TB
select 'a',10 union all
select 'b',20 union all
select 'c',3 union all
select 'd',8
--2000
select *,ID=(select count(1) from TB where [name]<=t.[name]) from TB t


--2005
select *,ID=Row_number() over(order by [name]) from TB

/*
name num ID
---- ----------- -----------
a 10 1
b 20 2
c 3 3
d 8 4

(4 行受影响)

*/
drop table TB

jimwoo 2009-09-24
  • 打赏
  • 举报
回复
写错了
select name, num, identity(int) as id into #tb from table1
select * from #tb
jimwoo 2009-09-24
  • 打赏
  • 举报
回复
sql2000插入到一个临时表
select name, num, identity(1) as id into #tb from table1
select * from #tb
--小F-- 2009-09-24
  • 打赏
  • 举报
回复
select name,num,ID=identity(int) into #t from table1
select * from #t
soft_wsx 2009-09-24
  • 打赏
  • 举报
回复
三连!或用子查询
soft_wsx 2009-09-24
  • 打赏
  • 举报
回复
2005用row_number,2000用临时表!
soft_wsx 2009-09-24
  • 打赏
  • 举报
回复

alter table tb add id int identity(1,1)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧