2011-05-05 82 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