当前位置: 代码迷 >> Sql Server >> sql怎么将纵向排列的各组数据,变为横向排列的?
  详细解决方案

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

热度:43   发布时间:2016-04-27 12:26:44.0
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*/
  相关解决方案