2017-03-07 151 views
1

我有一個查詢返回下面的第一個表,所以三列Var1(變量1),Var2 &協方差。顯示數據爲協方差矩陣

但是我想要做的是將數據以協方差矩陣的形式返回,如果可能的話?

Var1 Var2 Covariance 
ABC ABC 0.00213334 
DEF ABC 4.75E-05 
DEF DEF 0.0015896 
MNO ABC 0.00012669 
MNO DEF 0.000278643 
MNO MNO 0.001189053 
XYZ ABC 0.000456708 
XYZ DEF -0.00030231 
XYZ MNO -0.000390762 
XYZ XYZ 0.002947633 

結果我想,協方差矩陣。

 ABC  DEF  MNO  XYZ 
    ABC 0.0021 0.0000 0.0001 0.0005 
    DEF 0.0000 0.0016 0.0003 -0.0003 
    MNO 0.0001 0.0003 0.0012 -0.0004 
    XYZ 0.0005 -0.0003 -0.0004 0.0029 
+0

這種類型的轉換,則通常在應用層面更好。 –

回答

1

動態透視:

declare @cols nvarchar(max); 
declare @sql nvarchar(max); 
    select @cols = stuff((
    select distinct 
     ', ' + var1 
     from t 
     order by 1 
     for xml path (''), type).value('.','nvarchar(max)') 
    ,1,2,'') 
select @sql = ' 
select var2, ' + @cols + ' 
    from (
    select var1, var2, covariance=round(covariance,4) 
    from t 
    union all 
    select var2, var1, covariance=round(covariance,4) 
    from t 
    ) as t 
pivot (max([Covariance]) for [var1] in (' + @cols + ')) p' 
--select @sql 
exec(@sql); 

rextester演示:http://rextester.com/XTZ92563

retur NS:產生

+------+--------+---------+---------+---------+ 
| var2 | ABC | DEF | MNO | XYZ | 
+------+--------+---------+---------+---------+ 
| ABC | 0,0021 | 0  | 0,0001 | 0,0005 | 
| DEF | 0  | 0,0016 | 0,0003 | -0,0003 | 
| MNO | 0,0001 | 0,0003 | 0,0012 | -0,0004 | 
| XYZ | 0,0005 | -0,0003 | -0,0004 | 0,0029 | 
+------+--------+---------+---------+---------+ 

查詢:

select var2, ABC, DEF, MNO, XYZ 
    from (
    select var1, var2, covariance=round(covariance,4) 
     from t 
    union all 
    select var2, var1, covariance=round(covariance,4) 
     from t 
    ) as t 
pivot (max([Covariance]) for [var1] in (ABC, DEF, MNO, XYZ)) p 
0

如果你知道你有正好四個值,那麼你可以使用pivot或有條件聚集:

select max(case when col2 = 'ABC' then covariance else 0 end) as ABC, 
     max(case when col2 = 'DEF' then covariance else 0 end) as DEF, 
     max(case when col2 = 'MNO' then covariance else 0 end) as MNO, 
     max(case when col2 = 'XYZ' then covariance else 0 end) as XYZ 
from t 
group by col1; 

如果你有一個變量數列,那麼你可以在google的「SQL Server動態樞軸「 - 或者在更合適的應用程序中執行此操作。

+0

謝謝。我忘了說有可能會有新的變數。將谷歌的動態樞軸 – mHelpMe

0

使用PIVOT

示例腳本

Select var1,ABC,DEF,MNO,XYZ from (
Select 
var1, 
[1] ABC, 
[2] DEF, 
[3]MNO, 
[4]XYZ 
    from (
select 
Var1 , 
Covariance, 
ROW_NUMBER()OVER(PARTITION BY Var2 ORDER BY (select NULL))RN 
from 
    Table1)T 
PIVOT (MAX(Covariance) FOR RN IN ([1],[2],[3],[4]))PVT)T