2009-09-10 208 views
3

我有一個Entity-Value集合的表,並且希望透視結果。 以下是我正在尋找的效果,除非您看到使用公用表表達式的SELECT語句不能正確工作。 我的問題是:我在正確的軌道上,還是有一些簡單的樞軸命令?SQL Server 2005數據透視表問題

USE TempDB 
Declare @Person TABLE(
PersonID Int Identity(101,1)) 
INSERT INTO @Person DEFAULT VALUES 
INSERT INTO @Person DEFAULT VALUES 
INSERT INTO @Person DEFAULT VALUES 
INSERT INTO @Person DEFAULT VALUES 

DECLARE @Attribute TABLE(
AttributeID Int Identity(10,1) PRIMARY KEY, 
AttributeName Varchar(MAX)) 
INSERT INTO @Attribute(AttributeName) VALUES('Firstname') 
INSERT INTO @Attribute(AttributeName) VALUES('Lastname') 

DECLARE @Pat TABLE(-- A Person's Attributes 
PatID Int Identity, 
PersonID Int, 
AttributeID Int, 
PatValue Varchar(MAX) 
) 
INSERT INTO @Pat(PersonID,AttributeID,PatValue) VALUES(101,10,'John') 
INSERT INTO @Pat(PersonID,AttributeID,PatValue) VALUES(102,10,'Paul') 
INSERT INTO @Pat(PersonID,AttributeID,PatValue) VALUES(103,10,'George') 
INSERT INTO @Pat(PersonID,AttributeID,PatValue) VALUES(104,10,'Ringo') 
INSERT INTO @Pat(PersonID,AttributeID,PatValue) VALUES(101,11,'Lennon') 
INSERT INTO @Pat(PersonID,AttributeID,PatValue) VALUES(102,11,'McCartney') 
INSERT INTO @Pat(PersonID,AttributeID,PatValue) VALUES(103,11,'Harrison') 

SELECT Pat.PersonID,AttributeName,PatValue 
FROM @Pat Pat 
INNER JOIN @Person Person 
ON Pat.PersonID = Person.PersonID 
INNER JOIN @Attribute Attribute 
ON Pat.AttributeID=Attribute.AttributeID 
-- 

;WITH CTE1 AS(
    SELECT PersonID,PatValue AS FirstName 
    FROM @Pat Pat 
    INNER JOIN @Attribute Attribute 
    ON Pat.AttributeID=Attribute.AttributeID 
    WHERE AttributeName='FirstName' 
) 
,CTE2 AS(
    SELECT PersonID,PatValue AS LastName 
    FROM @Pat Pat 
    INNER JOIN @Attribute Attribute 
    ON Pat.AttributeID=Attribute.AttributeID 
    WHERE AttributeName='LastName' 
) 
SELECT Pat.PersonID,FirstName,LastName 
FROM @Pat Pat 
LEFT OUTER JOIN CTE1 
ON Pat.PersonID=CTE1.PersonID 
LEFT OUTER JOIN CTE2 
ON Pat.PersonID=CTE2.PersonID 
ORDER BY PersonID 

我只想要一個4人名單,他們的名字和姓氏。

+0

+1實際測試代碼重現問題 – 2009-09-10 21:25:42

回答

3

很好的例子Here

你的情況的查詢應該是這樣的:

SELECT PersonId, FirstName, LastName 
FROM 
(
    -- your query 
    SELECT Pat.PersonID,AttributeName,PatValue 
    FROM @Pat Pat 
    INNER JOIN @Person Person 
    ON Pat.PersonID = Person.PersonID 
    INNER JOIN @Attribute Attribute 
    ON Pat.AttributeID=Attribute.AttributeID 
) up 
PIVOT (MAX(PatValue) FOR AttributeName IN (FirstName, LastName)) AS pvt 
+0

在樞軸條款,你必須硬編碼「姓」和「LastName」)。如果要檢索的屬性和數據透視只能在運行時確定,這很難實現。 – 2009-09-10 21:57:59