2011-05-05 87 views
1

我有一个类型为varchar的列的表。如何转动它们。枢轴Sql服务器

我的表最初看起来像

Product Id Name      Value 

P1  Version Type   v1 

P1  License Type    POS 

P1  Product Description  This is P1 

我想转这产生以下

Product Id Version Type License Type Product Description 

P1   v1   POS  This is P1 

回答

0
SELECT t1.ProductId, t2.VersionType, t3.LicenceType, t4.ProductDescription 
FROM table t1 
LEFT JOIN table t2 on t1.ProductId = t2.ProductId 
        AND t2.Name = 'Version Type' 
LEFT JOIN table t3 on t1.ProductId = t3.ProductId 
        AND t3.Name = 'License Type' 
LEFT JOIN table t4 on t1.ProductId = t4.ProductId 
        AND t4.Name = 'Product Description' 
WHERE t1.ProductId = ? 
+0

而不是'FROM表t1',最好有:'FROM(SELECT DISTINCT产品编号FROM表)t1',如果我们想拥有所有产品数据透视查询。 – 2011-05-05 23:27:21

+0

我认为这是一个关键(独特的)。如果不是,你的'DISTINCT'是个好主意。 – manji 2011-05-05 23:33:48

0

你可以使用任何提及以下方式获得所需的结果。

Select ProductID, 
    Min(Case Name When 'Version Type' Then Value End) [Version Type], 
    Min(Case Name When 'License Type' Then Value End) [License Type], 
    Min(Case Name When 'Product Description' Then Value End) [Product Description] 
From <TABLE NAME> 
Group By ProductID 

或使用Pivot查询

select * from (select ProductID, name, value from <TABLENAME>) as tbl 
Pivot 
(
max(value) 
for name in ([Version Type], [License Type], [Product Description]) 
) as p