Is there a way to pivot an Entity-Attribute table? I want to flip all the rows into columns, regardless of how many different attributes there are.
Here's an example of what I want to accomplish. The example uses two attributes: FirstName, LastName. But in the real database, there are thousands of attributes and I want to flip them into columns for reporting purposes.
I don't want to have to write a CTE for every attribute.
USE TempDB
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 @tbl TABLE(
AttributeID Int,
EntityValue Varchar(MAX)
)
INSERT INTO @tbl(AttributeID,EntityValue) VALUES(10,'John')
INSERT INTO @tbl(AttributeID,EntityValue) VALUES(10,'Paul')
INSERT INTO @tbl(AttributeID,EntityValue) VALUES(10,'George')
INSERT INTO @tbl(AttributeID,EntityValue) VALUES(10,'Ringo')
INSERT INTO @tbl(AttributeID,EntityValue) VALUES(11,'Lennon')
INSERT INTO @tbl(AttributeID,EntityValue) VALUES(11,'McCartney')
INSERT INTO @tbl(AttributeID,EntityValue) VALUES(11,'Harrison')
SELECT A.AttributeID,AttributeName,EntityValue FROM @tbl T
INNER JOIN @Attribute A
ON T.AttributeID=A.AttributeID
DECLARE @Tbl2 Table(
FirstName Varchar(MAX),
LastName Varchar(MAX)
)
INSERT INTO @Tbl2(FirstName,LastName) VALUES('John','Lennon')
INSERT INTO @Tbl2(FirstName,LastName) VALUES('Paul','McCartney')
INSERT INTO @Tbl2(FirstName,LastName) VALUES('George','Harrison')
INSERT INTO @Tbl2(FirstName) VALUES('Ringo')
SELECT * FROM @Tbl2