34,588
社区成员
发帖
与我相关
我的任务
分享
测试数据
表Table1
col1 col2 col3 InOut
a1 b1 c1 In
a2 b2 c2 Out
a3 b3 c3 In
a4 b4 c5 Out
需要以下结果
表Table1
col1In col2In col3In col1Out col2Out col3Out
a1 b1 c1 a2 b2 c2
a3 b3 c3 a4 b4 c4
create table #tab(col1 varchar(20),col2 varchar(20),col3 varchar(20),InOut varchar(20))
insert into #tab
select 'a1','b1','c1','In' union all
select 'a2','b2','c2','Out' union all
select 'a3','b3','c3','In' union all
select 'a4','b4','c5','Out'
select a.col1in,a.col2in,a.col3in,b.col1out,b.col2out,b.col3out from
(
select ROW_NUMBER()over(order by col1)id,col1 as col1in,col2 as col2in,col3 as col3in from #tab where InOut='in'
)a
left join
(
select ROW_NUMBER()over(order by col1)id,col1 as col1out,col2 as col2out,col3 as col3out from #tab where InOut='out'
)b on a.id=b.id
---------------------------------------------------------------------
col1in col2in col3in col1out col2out col3out
-------------------- -------------------- -------------------- -------------------- -------------------- --------------------
a1 b1 c1 a2 b2 c2
a3 b3 c3 a4 b4 c5
(2 行受影响)
create table Table1
(col1 varchar(5),col2 varchar(5),col3 varchar(5),InOut varchar(5))
insert into Table1
select 'a1', 'b1', 'c1', 'In' union all
select 'a2', 'b2', 'c2', 'Out' union all
select 'a3', 'b3', 'c3', 'In' union all
select 'a4', 'b4', 'c4', 'Out'
select a.col1In,a.col2In,a.col3In,
b.col1Out,b.col2Out,b.col3Out
from
(select col1 'col1In',col2 'col2In',col3 'col3In',
row_number() over(order by getdate()) 'rn'
from Table1 where InOut='In') a
inner join
(select col1 'col1Out',col2 'col2Out',col3 'col3Out',
row_number() over(order by getdate()) 'rn'
from Table1 where InOut='Out') b on a.rn=b.rn
/*
col1In col2In col3In col1Out col2Out col3Out
------ ------ ------ ------- ------- -------
a1 b1 c1 a2 b2 c2
a3 b3 c3 a4 b4 c4
(2 row(s) affected)
*/
;with cte(col1,col2,col3,InOut ) as
(
select 'a1','b1','c1','In'
union all select 'a2','b2','c2','Out'
union all select 'a3','b3','c3','In'
union all select 'a4','b4','c5','Out'
)
select a.col1 as col1In,a.col2 as col2In,a.col3 as col3In,
b.col1 as col1Out,b.col2 as col2Out,b.col3 as col3Out
from (select *,rn=ROW_NUMBER() over(order by getdate()) from cte where InOut='In')a
left join (select *,rn=ROW_NUMBER() over(order by getdate()) from cte where InOut='Out')b
on a.rn=b.rn
/*
col1In col2In col3In col1Out col2Out col3Out
a1 b1 c1 a2 b2 c2
a3 b3 c3 a4 b4 c5
*/