SQL pivoting - 如何获得要旋转的多个列之间的所有可能组合

时间:2017-10-28 13:03:22

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

这是我的源表(pivot_dummy):

input data

我需要通过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

但这并没有给我所需的输出,而是省略了资产/指示之间的各种组合。我也不确定如果有更多列进入(这是非常可能的)它将如何工作,因此我正在寻找一个通用解决方案,它可以根据公共{{1}找到所有param_type列之间的可能组合}。

任何帮助都将非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

这比上一个问题更棘手,因为并非所有ID都具有所有值。

诱惑是:

select pd1.nct_id, pd1.parameter_value as asset, pd2.parameter_value as indication,
       pd3.parameter_value as BMx, pd4.parameter_value as LOT
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' join
     pivot_dummy pd3
     on pd1.nct_id = pd3.nct_id and
        pd3.parameter_type = 'BMx' join
     pivot_dummy pd4
     on pd1.nct_id = pd4.nct_id and
        pd4.parameter_type = 'LOT';

这仅适用于具有所有四个值的ID。切换到full join可以解决问题 - 但会使查询复杂化。

我认为最好的解决方案是left join,如下所示:

select pd.nct_id, pd1.parameter_value as asset, pd2.parameter_value as indication,
       pd3.parameter_value as BMx, pd4.parameter_value as LOT
from (select distinct nct_id from pivot_dummy
     ) pd left join
     pivot_dummy pd1
     on pd1.nct_id = pd.nct_id and
        pd1.parameter_type = 'Asset' left join
     pivot_dummy pd2
     on pd2.nct_id = pd.nct_id and
        pd2.parameter_type = 'Indication' left join
     pivot_dummy pd3
     on pd3.nct_id = pd.nct_id and
        pd3.parameter_type = 'BMx' left join
     pivot_dummy pd4
     on pd4.nct_id = pd.nct_id and
        pd4.parameter_type = 'LOT';