Solution: I wasn't able to solve this without going beyond a simple query, so I've resorted to hard-coding the case statements up to the limit of my table's numeric identifier.
I'm looking for help in writing a query to represent an unknown number of records across multiple fields with only one record per Primary Key.
Here's my table design:
[Column Name] | [Data Type] | [Allow Nulls]
-------------------------------------------
*ItemRef nvarchar(48) Unchecked
*AttributeID numeric(2, 0) Unchecked
AttributeName nvarchar(128) Unchecked
AttributeValue nvarchar(3072) Nullable
AttributeUOM nvarchar(10) Nullable
*EDIT: Here's some sample data:
Product123 | 1 | Brand | MyBrandName
Product123 | 2 | Product Line | MyProductLine
Product123 | 3 | Color | MyColor
Product456 | 1 | Brand | MySecondBrandName
Product456 | 2 | Style | MyStyle
Here's My Desired Query Result:
[ItemRef] | [AttributeName_01] | [AttributeValue_01] | [AttributeName_02] | [AttributeValue_02] | etc...
At first I thought to use a PIVOT query, but ran across multiple threads on here suggesting I try Aggregate Case statements instead, which works much more efficiently at first glance.
However, I don't know how many attributes a single record gets. So my question is, how can I write the following to better represent an uncertain amount of attributes?
SELECT ItemRef
, MIN(CASE AttributeID WHEN '1' THEN AttributeName END) AS AttrName01
, MIN(CASE AttributeID WHEN '1' THEN AttributeValue END) AS AttrValue01
, MIN(CASE AttributeID WHEN '1' THEN AttributeUOM END) AS AttrUom01
, MIN(CASE AttributeID WHEN '2' THEN AttributeName END) AS AttrName02
, MIN(CASE AttributeID WHEN '2' THEN AttributeValue END) AS AttrValue02
, MIN(CASE AttributeID WHEN '2' THEN AttributeUOM END) AS AttrUom02
, MIN(CASE AttributeID WHEN '3' THEN AttributeName END) AS AttrName03
, MIN(CASE AttributeID WHEN '3' THEN AttributeValue END) AS AttrValue03
, MIN(CASE AttributeID WHEN '3' THEN AttributeUOM END) AS AttrUom03
, MIN(CASE AttributeID WHEN '4' THEN AttributeName END) AS AttrName04
, MIN(CASE AttributeID WHEN '4' THEN AttributeValue END) AS AttrValue04
, MIN(CASE AttributeID WHEN '4' THEN AttributeUOM END) AS AttrUom04
. . .
, MIN(CASE AttributeID WHEN '99' THEN AttributeName END) AS AttrName05
, MIN(CASE AttributeID WHEN '99' THEN AttributeValue END) AS AttrValue05
, MIN(CASE AttributeID WHEN '99' THEN AttributeUOM END) AS AttrUom05
FROM dbo.ProductAttributes
GROUP BY ItemRef