首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

【一个比较简单Sql来见见】

2013-10-16 
【一个比较简单Sql来看看】测试数据表Table1col1col2col3InOut a1b1c1In a2b2c2Out a3b3c3In a4b4c5Out需要

【一个比较简单Sql来看看】


测试数据
表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

/*
col1Incol2Incol3Incol1Outcol2Outcol3Out
a1b1c1a2b2c2
a3b3c3a4b4c5
*/

热点排行