SQL pivot - 如何获得要透视的列之间的所有可能组合

时间:2017-10-28 11:30:04

标签: sql sql-server combinations multiple-columns partitioning

这是我的源表(pivot_dummy):

Source data Table

我需要通过Parameter_type来转动它,但需要在Parameter_val之间进行所有可能的组合。像这样的东西

Desired Output

我正在使用此代码来完成它:

SELECT nct_id, [Asset],[Indication], rowid
FROM (SELECT nct_id,Parameter_val,parameter_type, rowid
      FROM (Select *,
                   Row_Number() Over (Partition By nct_id,Parameter_type ORDER BY nct_id) RowId 
            from [dbo].[pivot_dummy]
           ) a 
     ) s
Pivot (
    max(parameter_val)
        for Parameter_type in ([Asset], [Indication])
    ) as pivottable

但是此代码会产生以下结果:

Current Output

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

据我所知,你根本不需要pivot。只需join

select pd1.nct_id, pd1.parameter_value as asset, pd2.parameter_value as indication
from pivot_dummy pd1 join
     pivot_dummy pd2
     on pd1.nct_id = pd2.nct_id and
        pd1.parameter_type = 'Asset' and
        pd2.parameter_type = 'Indication';