2014-01-24 19 views
0

我有表呼叫Specf和我有一个视图View1并使用这两个我需要生成所需的输出。如何在数据透视表中显示SQL Server中的重复值

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 

回答

1
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 
+0

我需要生成动态 – user2307049

+0

@user好了,是的,这是可能的。做一个动态数据透视的搜索,看看不同的方式来实现。最后需要的查询是我在这个答案中提供的。 –