日期:2014-05-17 浏览次数:20592 次
测试数据
表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
;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
*/