I asked a similar question [here]: Transposing groups of rows with the same ID into another table
but I don't want to have to write out each line for each attribute name. I want to be able to take rows in one column from TABLE1 (say there's 50 unique rows) and transpose them efficiently into TABLE2.
This is a small example of a table of ATTR_NMEs (attribute names) in one column:
ID ATTR_NME ATTR_VAL
1000 UPC 00015582981001
1000 Price 15.99
1000 Brand Oreo
1005 UPC 00038762291010
1005 Price 12.50
1005 Brand Sargento
1010 UPC 00198872499000
1010 Price 4.99
1010 Brand Olay
So ID, UPC, Price, and Brand should be their own columns with the ATTR_VAL as the rows of data. HERE'S THE DIFFERENCE BETWEEN THIS QUESTION AND MY PREVIOUS ONE: say I have a table with 50 different ATTR_NMEs, I want to use that column of data with all those attribute names to create the new tranposed table without having to write the following 50 times for the different attributes:
MAX(CASE WHEN ATTR_NME = 'UPC' THEN ATTR_VAL END) AS UPC
I tried to declare a variable for the rows in the ATTR_NME column like this:
DECLARE @itm varchar(100);
SET @itm = (
SELECT ATTR_NME
FROM TABLE1
);
SELECT ID,
MAX(CASE WHEN ATTR_NME = @itm THEN ATTR_VAL END) AS [@itm]
FROM TABLE1
GROUP BY ID;
But that didn't work for multiple reasons; one being it wanted me to wrap an aggregate function around ATTR_NME where I SET @itm (but then I only got one attribute name). It also didn't label/name the column as I wanted it to. Is it even possible to do what I want to do? If so, how? TIA.