日期:2014-05-18  浏览次数:20469 次

sql如何将纵向排列的各组数据,变为横向排列的??
比如,原数据集为

code return dummy year

 1 0.35 0 2004

 2 0.86 1 2005

 3 1.92 0 2006

 4 2.34 0 2005

 5 0.19 1 2006


目标数据集:

code return dummy year code return dummy year  
 1 0.35 0 2004 4 2.34 0 2005
 2 0.86 1 2005 5 0.19 1 2006 
 3 1.92 0 2006  


------解决方案--------------------
如果你使用的是sql server2005或者更高级的版本,也许篇文章会对你有帮助!

http://www.cnblogs.com/kerrycode/archive/2010/07/28/1786547.html

good luck!
------解决方案--------------------
SQL code
SELECT 
*
FROM 
   (SELECT * FROM TB WHERE ((CODE - 1) / 3) % 2 = 0) AS A
LEFT JOIN 
   (SELECT * FROM TB WHERE ((CODE - 1) / 3) % 2 = 1 ) AS B
ON 
   (A.CODE - 1) / 3 = (B.CODE - 1) / 3 -1 AND (A.CODE - 1) % 3 = (B.CODE - 1) % 3

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null 
drop table [test]
create table [test](
[code] int,
[return] numeric(3,2),
[dummy] int,
[year] int
)
insert [test]
select 1,0.35,0,2004 union all
select 2,0.86,1,2005 union all
select 3,1.92,0,2006 union all
select 4,2.34,0,2005 union all
select 5,0.19,1,2006
go

select * from 
(select * from test where ((code-1)/3)%2=0) as a
left join 
(select * from test where ((code -1)/3)%2=1) as b
on (a.code-1)/3 =(b.code-1)/3 -1 and (a.code-1)%3=(b.code-1)%3
/*
code    return    dummy    year    code    return    dummy    year
----------------------------
1    0.35    0    2004    4    2.34    0    2005
2    0.86    1    2005    5    0.19    1    2006
3    1.92    0    2006    NULL    NULL    NULL    NULL
*/