求一sql语句。(有点难)(万分感谢)

zzzl 2003-11-20 11:56:12
用sql语句根据一个表得出如下的数据,col1的值是递增的。

col1 表中的原有列1 表中的原有列2
---------------------------------------------------
1
2
3
...
记录总数
...全文
47 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunshareforever 2003-11-20
  • 打赏
  • 举报
回复
select col = identity(int,1,1) ,col1,col2 into #t from 表
txlicenhe 2003-11-20
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/2437/2437014.xml?temp=.67857
交流]自增号

1: 自增列 类型为:int identity(1,1) 当然也可以是bigint,smallint
eg: create table tbName(id int identity(1,1),description varchar(20))
或在用企业管理器设计表字段时,将字段设为int,将标识设为是,其它用默认即可

2: 查询时加序号:
a:没有主键的情形:
Select identity(int,1,1) as iid,* into #tmp from TableName
Select * from #tmp
Drop table #tmp
b:有主键的情形:
Select (Select sum(1) from TableName where KeyField <= a.KeyField) as iid,* from TableName a
zjcxc 元老 2003-11-20
  • 打赏
  • 举报
回复
--上面是针对原表中无主键(或不重复的字段)的情况,如果你的表中有主键,可以用:

select col1=(select sum(1) from 原表 where 主键<=a.主键),表中的原有列1,表中的原有列2 from 原表 a order by 主键
zjcxc 元老 2003-11-20
  • 打赏
  • 举报
回复
select col1=identity(int,1,1),表中的原有列1,表中的原有列2 into #t from 原表

select * from #t

drop table #t
realgz 2003-11-20
  • 打赏
  • 举报
回复
据说
select (select count(*) from 原表 where 有顺序的可以唯一标识一条记录的列或列的组合<=tem.有顺序的可以唯一标识一条记录的列或列的组合) col1,* from 原表 tem
效率更高。
LoveSQL 2003-11-20
  • 打赏
  • 举报
回复
select IDENTITY(int, 1,1) AS ID_Num,* into #temp from 表
select * from #temp
pengdali 2003-11-20
  • 打赏
  • 举报
回复
select (select sum(1) from 原表 where 有顺序的可以唯一标识一条记录的列<=tem.有顺序的可以唯一标识一条记录的列) col1,* from 原表 tem
Benimarunikado 2003-11-20
  • 打赏
  • 举报
回复
--根据作者意图,实现如下:

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'T1')
DROP TABLE T1
GO

CREATE TABLE T1 ( column_1 int, column_2 varchar(30))

GO

INSERT T1 SELECT 1, 'Row #1'
UNION ALL SELECT 4, 'Row #2'
UNION ALL SELECT 12, 'Row #3'
UNION ALL SELECT 53, 'Row #4'

GO

ALTER TABLE T1 ADD col1 INT IDENTITY

GO

--最终查询语句:

SELECT col1,column_1,column_2 FROM T1

SELECT COUNT(*)FROM T1

--结果集:

col1 column_1 column_2
----------- ----------- ---------
1 1 Row #1
2 4 Row #2
3 12 Row #3
4 53 Row #4

(所影响的行数为 4 行)


-----------
4

(所影响的行数为 1 行)

--删除测试环境

DROP TABLE T1
pengdali 2003-11-20
  • 打赏
  • 举报
回复
select IDENTITY(int, 1,1) AS ID_Num,* into #temp from 表
select * from #temp
orcale 2003-11-20
  • 打赏
  • 举报
回复
用臨時表.增加indentity欄位即可

34,875

社区成员

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

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