日期:2014-05-17 浏览次数:20473 次
drop table tb
create table tb(ID int,aaa varchar(10))
insert into tb
select 1,'aa'
go 1000
insert into tb
select 1,'bb'
go 1000
insert into tb
select 1,'cc'
go 1000
select *,
right('00'+cast((ROW_NUMBER() over(order by @@servername)-1)/1000+1 as varchar),2) as group_num
from tb
WITH a1 AS
(
SELECT *,ROW_NUMBER() OVER (ORDER BY @@servername) re
FROM 表
)
SELECT *,re-CASE re%1000 WHEN 0 THEN re%1000+1000 else re%1000 end 组号
FROM a1
-- 建测试表
create table 一个表(id int)
create table 另一个表(组号 varchar(5),id int)
-- 产生3000笔记录
set nocount on
declare @i int
select @i=1
while(@i<=3000)
begin
insert into 一个表(id) values(@i)
select @i=@i+1
end
set nocount off
-- 按照顺序分组插入到另一个表中, 每组1000条,组号01,02,03
insert into 另一个表(组号,id)
select '0'+rtrim(((row_number() over(order by getdate())-1)/1000)+1),id
from 一个表
-- 结果
select 组号,
min(id) 'min_id',
max(id) 'max_id'
from 另一个表
group by 组号
order by 组号
/*
组号 min_id max_id
----- ----------- -----------
01 1 1000
02 1001 2000
03 2001 3000
(3 row(s) affected)
*/