2010-06-15 74 views
-1

我们可以在标准SQL2005/2008中做矩阵转置(行成为列,列成为行)吗?矩阵转置TSQL

 
1 2 3 4 5 
4 5 6 6 7 
7 8 9 8 9 
1 3 4 5 6 
2 4 5 6 7

变化

1 4 7 1 2 
2 5 8 3 4 
3 6 9 5 6 
4 6 8 5 6 
5 7 9 6 7

怎么没有行< >没有列的?

让我们考虑它的固定行数。

回答

0
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Result]') AND type in (N'U')) 
DROP TABLE [dbo].[Result] 
GO 

CREATE TABLE [dbo].[Result](
    [RN] [int] NULL, 
    [1] [int] NULL, 
    [2] [int] NULL, 
    [3] [int] NULL, 
    [4] [int] NULL, 
    [5] [int] NULL 
) ON [PRIMARY] 

GO 

insert into Result 
select 1,11,12,13,14,15 
union all 
select 2,21,22,23,24,25 
union all 
select 3,31,32,33,34,35 
union all 
select 4,41,42,43,44,45 
union all 
select 5,51,52,53,54,55 

select * from Result 


;WITH Preresult AS 
(SELECT RN AS Row, 
    Col, 
    Val 
FROM Result 
UNPIVOT (Val FOR Col IN ([1],[2],[3],[4],[5])) unpvt 
) 
--select * from Preresult 
--Transform array into matrix 
SELECT 
    Col as Row, 
    [1], 
    [2], 
    [3], 
    [4], 
    [5] 

FROM 
    (
     SELECT Row, Col, Val FROM Preresult) t1 
     PIVOT 
     (MAX(Val) 
     FOR Row IN ([1],[2],[3],[4],[5]) 
     ) AS pvt 
ORDER BY Row;-->replace Col for column sorting 

来源:http://www.devx.com/dbzone/Article/40223/1763?supportItem=5

+0

什么是错的这个答案,它工作正常,测试成功。请你解释一下为什么我在这方面得到了肯定。 – rmdussa 2010-06-17 05:32:51

+0

你的回答没有提供关于代码如何工作的解释,所以这可能是为什么它被拒绝投票。 – afuzzyllama 2014-07-16 16:01:38

0

,如果你的数据在表格您可能要重新格式化你的问题,而是一个变换很简单:

CREATE TABLE matrix (Row int NOT NULL, Column int NOT NULL, Value <datatype> NOT NULL) 

SELECT Row AS Column 
     ,Column AS Row 
     ,Value 
FROM matrix