SQL使用序列号插入临时表

时间:2014-08-25 10:52:16

标签: sql

我有一个简单的SQL查询,如:

Select Distinct GroupCode 
Into   #TempTable
From   MyTable
SELECT * FROM #TempTable
drop Table #TempTable

其OutPut为

enter image description here

现在,我还需要一个序列号列,如1,2,3 ....在Out put中。

我怎样才能做到这一点?

由于

2 个答案:

答案 0 :(得分:2)

只需添加row_number()

select row_number() over (order by (select NULL)) as id, GroupCode 
into   #TempTable
from   (select distinct GroupCode from MyTable) t;

select *
from #TempTable;

drop Table #TempTable;

答案 1 :(得分:1)

您可以显式创建临时表,并为序列号添加IDENTITY列,如下所示:

create table #tmp(id int identity(1,1), groupcode uniqueidentifier)

insert into #tmp (groupcode)
Select Distinct GroupCode
from mytable

select * from #tmp
order by id

drop table #tmp