如何在SQL Server中的Pivot表中显示重复值



我的表呼叫Specf,我有一个视图View1,并且使用这两个我需要生成所需的输出。

SPECf

P1 
P2
P3
P4
P5

View1

Product SPESET      SPECf          Value 
A1      ABCSET       P1         C1
A1      ABCSET       P2         C2
A1      XYZSET       P3         C2
A2      ABXSET       P1         C1
A2      ABXSET       P4         C4
A2      ABXSET       P2         C1
A3      CDESET       P5         C2

所需的输出:

Product SPESET      SPE_P1   SPE_P2    SPE_P3    SPE_P4    SPE_P5 
A1      ABCSET       C1         C2       C2       null       null
A1      ABCSET       C1         C2       C2       null       null
A1      XYZSET       C1         C2       C2       null       null
A2      ABXSET       C1         C1       null      c4        null
A2      ABXSET       C1         C1       null      c4        null
A2      ABXSET       C1         C1       null      c4        null
A3      CDESET       null      null      null     null       c2
select V2.Product,
       V2.SPESET,
       P.P1 SPE_P1,
       P.P2 SPE_P2,
       P.P3 SPE_P3,
       P.P4 SPE_P4,
       P.P5 SPE_P5 
from  (
      select V1.Product, V1.SPECf, V1.Value
      from View1 as V1
      ) as V1
pivot (
      max(V1.Value) 
      for V1.SPECf in (P1, P2, P3, P4, P5)
      ) as P
inner join View1 as V2
  on P.Product = V2.Product

最新更新