我正在尝试在SQL Server中获取关联矩阵,并且我的数据在表中的方式如下:
RptLOB1 RptLOB2 Correlation
AE AE 1
Bail AE 0.35
Commercial Bail 0.25
Commercial AE 0.15
......等等。
我想写一个代码,所以我的输出看起来如下:
AE Bail Commercial
AE 1 0.35 0.15
Bail 0.35 1 0.25
Commercial 0.15 0.25 1
只要订单从上到下,从左到右在顶部,RptLOB的顺序无关紧要。我一直试图找到一种方法来解决这个问题,我不太清楚最好的方法是什么。我在考虑使用PIVOT,但不会输出RptLOB(它们将被视为表中的列)。
编辑:
此输出将插入另一个表中,如下所示:
col1 col2 col3 col4 col5
Generic
Company Inputs Insurance Stochastic Model Correlations Exposure Correlation Matrix
AE Bail Commercial
AE 1 0.35 0.15
Bail 0.35 1 0.25
Commercial 0.15 0.25 1
答案 0 :(得分:5)
您可以使用PIVOT
。如果您知道必须转换的列数,则可以使用静态版本:
select *
from
(
select RptLOB1 RptLOB1, RPTLOB2 RPTLOB2, Correlation
from yourtable
union all
select RPTLOB2, RptLOB1, Correlation
from yourtable
union all
select distinct RptLOB1, RptLOB1, 1.0
from yourtable
) x
pivot
(
max(Correlation)
for RPTLOB2 in ([AE], [Bail], [Commercial])
) p;
如果要关联的值的数量未知,则需要使用动态版本:
DECLARE @query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT distinct ','
+ quotename(RptLOB1)
from yourtable t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select RptLOB1, '+@colspivot+ '
from
(
select RptLOB1 RptLOB1, RPTLOB2 RPTLOB2, Correlation
from yourtable
union all
select RPTLOB2, RptLOB1, Correlation
from yourtable
union all
select distinct RptLOB1, RptLOB1, 1.0
from yourtable
) x
pivot
(
max(Correlation)
for RPTLOB2 in ('+ @colspivot +')
) p'
exec(@query)
编辑 - 根据您的评论,如果您希望列标题位于另一行,则可以使用以下内容:
DECLARE @query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX),
@colsRow as NVARCHAR(MAX),
@colsConverted as NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT distinct ','
+ quotename(RptLOB1)
from yourtable t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsRow = STUFF((SELECT distinct ', '''
+ RptLOB1 + ''' as ' + RptLOB1
from yourtable t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsConverted
= STUFF((SELECT distinct ', CAST('
+ quotename(RptLOB1)
+ ' as varchar(50))'
from yourtable t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select ''RptLOB1'' as RptLOB1,
'+ @colsRow + '
union all
select RptLOB1, '+ @colsConverted+ '
from
(
select RptLOB1 RptLOB1, RPTLOB2 RPTLOB2, Correlation
from yourtable
union all
select RPTLOB2, RptLOB1, Correlation
from yourtable
union all
select distinct RptLOB1, RptLOB1, 1.0
from yourtable
) x
pivot
(
max(Correlation)
for RPTLOB2 in ('+ @colspivot +')
) p'
exec(@query)
答案 1 :(得分:0)
问题是您的数据不够完整。所以,用你需要的东西来增强它:
with d as (
select RptLOB1, RptLOB2, Correlation from t union all
select RptLOB2, RptLOB1, Correlation from t union all
select distinct RptLob1, RptLob1, 1.0 from t
)
select RptLOB1, RptLOB2, Corr
from d
pivot (max(correlation) for val in ('AE', 'Bail', 'Commercial')) as corr
如果您不知道所有值的名称,那么一般情况下您将需要动态SQL。