日期:2014-05-17  浏览次数:20675 次

如何获得一个表中的奇数行的数据和偶数行的数据
就是有个表。
比如
talbe_1
words
你好
hello
你好1
hello1
你好2
hello2
你好3
hello3
你好4
hello4
我想将table_1中的奇数行和偶数行分别获得并放到两个DataTable里面
求sql 语句,谢谢。
------最佳解决方案--------------------
alter tb add id int identity(1,1)
go
select col into  tb1 from tb where id%2=1
select col into  tb2 from tb where id%2=0

------其他解决方案--------------------

with sel as(
select words,rn=row_number()over(order by getdate()) from tb
)
insert into tb1
select words from sel where rn%2=1
with sel as(
select words,rn=row_number()over(order by getdate()) from tb
)
insert into tb2
select words from sel where rn%2=2

------其他解决方案--------------------
用row_number()来加一个虚拟id,然后再计算奇偶
------其他解决方案--------------------
create table #table_1(words nvarchar(20))
insert into #table_1
(words) values('你好'),('hello'),('你好1'),('hello1'),('你好2'),('hello2'),('你好3'),('hello3'),('你好4'),('hello4')

create table #test1(words nvarchar(20))
create table #test2(words nvarchar(20))

declare @news varchar(20)
declare @s varchar(20)
declare youbiao1 cursor for
select words from #table_1 where(PATINDEX('%[0-9]%',words)>0 )
OPEN youbiao1
FETCH NEXT FROM youbiao1 INTO @s
WHILE(@@FETCH_STATUS = 0)
begin
set @news=@s
WHILE PATINDEX('%[^0-9]%',@news) > 0
BEGIN
set @news=stuff(@news,patindex('%[^0-9]%',@news),1,'')
END
if @news%2=1
insert into #test1(words)values(@S)
else if @news%2=0
insert into #test2(words) values(@S)
FETCH NEXT FROM youbiao1 INTO @s 
  END
CLOSE youbiao1
DEALLOCATE youbiao1


select * from #test1
select * from #test2


比较菜,搞了半天别见笑
------其他解决方案--------------------

if OBJECT_ID('table1','u') is not null
drop table table1
create table table1
(
Name nvarchar(20) ,


if OBJECT_ID('table2','u') is not null
drop table table2
create table table2
(
Name nvarchar(20) ,


go
with T as 
(select Name,ROW_NUMBER() over (order by getdate()) RowID from Course)
insert into Table1 select Name From T where RowID%2=0

go
with T as 
(select Name,ROW_NUMBER() over (order by getdate()) RowID from Course)
insert into table2 select Name From T where RowID%2=1

go

select *From Course
select *From table1
select *From table2

--Course
--1001 数据结构 10001
--1002 计算机网络 10001