Hi,
I would suggest you to use a dynamic PIVOT with partitioning to transpose data. Here's how to do that:
CREATE TABLE #DataTable (Attribute_SubID INT, AttributeID INT, Attribute_Sub NVARCHAR(50));
INSERT INTO #DataTable (Attribute_SubID, AttributeID, Attribute_Sub) VALUES (3, 2, 'xyz'), (4, 2, 'abc'), (3, 2, 'def');
DECLARE @ColumnsTable TABLE (Col VARCHAR(10));
INSERT INTO @ColumnsTable (Col)
SELECT DISTINCT Attribute_SubID FROM #DataTable;
DECLARE @SQL VARCHAR(MAX);
SET @SQL = ';WITH Data
AS
(
SELECT Attribute_SubID, Attribute_Sub, ROW_NUMBER() OVER (PARTITION BY Attribute_SubID
ORDER BY Attribute_SubID) AS RowNumber
FROM #DataTable
)
SELECT ' + (SELECT STUFF((SELECT ', ISNULL([' + Col + '], ''--'') AS [' + Col + ']'
FROM @ColumnsTable
FOR XML PATH('')), 1, 2, '')) +
'
FROM Data
PIVOT
(
MAX(Attribute_Sub)
FOR Attribute_SubID IN
(' + (SELECT STUFF((SELECT ', [' + Col + ']'
FROM @ColumnsTable
FOR XML PATH('')), 1, 2, '')) + ')
) AS pvt;';
EXEC(@SQL);
DROP TABLE #DataTable;
Result:
3 4
xyz abc
def --