動態透視:
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
這種類型的轉換,則通常在應用層面更好。 –