求SQL查询代码

cppsun 2011-04-21 10:51:12
id 字段1
2 4
3 5
4 7


要查询出来的记录是
序号 字段1
1 4
2 5
3 7

多一列'序号'这样的排序字段。
...全文
63 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2011-04-21
  • 打赏
  • 举报
回复
create table tb(id int,字段1 int)
insert into tb values(2 ,4)
insert into tb values(3 ,5)
insert into tb values(4 ,7)
go

select id = (select count(1) from tb where 字段1 < t.字段1) + 1 , 字段1 from tb t
/*
id 字段1
----------- -----------
1 4
2 5
3 7

(所影响的行数为 3 行)
*/

select id = isnull((select top 1 id from tb where 字段1 < t.字段1 order by 字段1 desc),1) , 字段1 from tb t
/*
id 字段1
----------- -----------
1 4
2 5
3 7

(所影响的行数为 3 行)
*/

drop table tb
叶子 2011-04-21
  • 打赏
  • 举报
回复

declare @t table (id int,字段1 int)
insert into @t
select 2,4 union all
select 3,5 union all
select 4,7

--SQL SERVER 2000
create table #t (id int identity,字段1 int)
insert into #t
select 字段1 from @t

select * from #t
drop table #t
/*
id 字段1
----------- -----------
1 4
2 5
3 7
*/
叶子 2011-04-21
  • 打赏
  • 举报
回复

declare @t table (id int,字段1 int)
insert into @t
select 2,4 union all
select 3,5 union all
select 4,7
--Sql server 2005+
select row_number() over (order by id ) as id,字段1 from @t
/*
id 字段1
-------------------- -----------
1 4
2 5
3 7
*/
kingtiy 2011-04-21
  • 打赏
  • 举报
回复

select row_number() over(order by 字段1) as 序号,字段1 from tb
叶子 2011-04-21
  • 打赏
  • 举报
回复
SQL 2000还是2005+?

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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