将数据显示为协方差矩阵

时间:2017-03-07 12:35:42

标签: sql sql-server

我有一个返回下面第一个表的查询,因此有三列,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

3 个答案:

答案 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

返回:

+------+--------+---------+---------+---------+
| 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

答案 1 :(得分: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;

如果您有可变数量的列,那么您可以谷歌" SQL Server动态数据透视" - 或者在更合适的应用程序中执行此操作。

答案 2 :(得分: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