我有一个稀疏填充的矩阵,它是一系列左连接的结果。我想将它折叠成一行(见下文)。我见过的唯一解决方案是PK上的GROUP BY和ColA上的MAX(),ColB等。性能是一个很大的问题,所以我想知道是否有人有更好的解决方案。列ColA,ColB等是已转动到列的行。我的理解是我不能使用PIVOT因为列来自行(1到n)并且可以在任何给定时间改变。
加入会生成SPM(不,我的表/列没有真正命名):
SELECT
mainTable.custNbr
, mainTable.custPartNbr
, [lkup colA].usr_def_attr as [colA]
, [lkup colB].usr_def_attr as [colB]
, [lkup colC].usr_def_attr as [colC]
, [lkup colD].usr_def_attr as [colD]
, [lkup colE].usr_def_attr as [colE]
FROM db2.dbo.table2 as mainTable
LEFT JOIN db1.dbo.lookup as [colA]
ON mainTable.lookupValue = [colA].lkup_id
and mainTable.cmply_typ_lkup_id = 166697
LEFT JOIN db1.dbo.lookup as [lkup colB]
ON mainTable.lookupValue = [lkup colB].lkup_id
and mainTable.cmply_typ_lkup_id = 166700
LEFT JOIN db1.dbo.lookup as [lkup colC]
ON mainTable.lookupValue = [lkup colC].lkup_id
and mainTable.cmply_typ_lkup_id = 166699
LEFT JOIN db1.dbo.lookup as [lkup colD]
ON mainTable.lookupValue = [lkup colD].lkup_id
and mainTable.cmply_typ_lkup_id = 166696
LEFT JOIN db1.dbo.lookup as [lkup colE]
ON mainTable.lookupValue = [lkup colE].lkup_id
and mainTable.cmply_typ_lkup_id = 166698
结果:
PKCol ColA ColB ColC ColD ColE
204045 NULL NULL NULL NULL 23
204045 NULL NULL NULL 35 NULL
204045 NULL NULL 35 NULL NULL
204045 NULL 23 NULL NULL NULL
204045 23 NULL NULL NULL NULL
期望的结果:
PKCol ColA ColB ColC ColD ColE
20405 23 23 35 35 23