读书人

sql怎么将纵向排列的各组数据变为横

发布时间: 2012-06-11 17:42:22 作者: rapoo

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 ALEFT JOIN    (SELECT * FROM TB WHERE ((CODE - 1) / 3) % 2 = 1 ) AS BON    (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 allselect 2,0.86,1,2005 union allselect 3,1.92,0,2006 union allselect 4,2.34,0,2005 union allselect 5,0.19,1,2006goselect * from (select * from test where ((code-1)/3)%2=0) as aleft join (select * from test where ((code -1)/3)%2=1) as bon (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    20052    0.86    1    2005    5    0.19    1    20063    1.92    0    2006    NULL    NULL    NULL    NULL*/ 

读书人网 >SQL Server

热点推荐