Обратите внимание, что результаты могут отличаться, поэтому я могу иметь 3 столбца или 4, 5 и т. Д. ... до 10 столбцов
Тогда вам нужен динамический SQL
DECLARE @Attributes VARCHAR(MAX), @SQL VARCHAR(MAX)
SELECT @Attributes = STUFF((SELECT ',' + QUOTENAME(Name)
FROM AttributeDefinitions
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SET @SQL = '
SELECT * FROM (
SELECT
jD.AccountID,
SUM(jD.Amount) AS [Total Dollars],
COA.Name,
SUM(jD.Qty) AS QTY,
CONVERT(date, GETDATE()) AS Date,
AttributeDefinitions.Name,
AttributeValues.Value
FROM
AttributeDefinitions INNER JOIN
AttributeCategories ON AttributeDefinitions.AttributeCategoryID = AttributeCategories.AttributeCategoryID INNER JOIN
AttributeValues ON AttributeDefinitions.AttributeDefinitionID = AttributeValues.AttributeDefinitionID RIGHT OUTER JOIN
JnlDetails AS jD WITH (NOLOCK) INNER JOIN
COA ON jD.AccountID = COA.AccountID ON AttributeValues.AttributeValueGroupID = COA.AttributeValueGroupID
WHERE
(jD.CreateDate >= GETDATE() - 2) AND
(jD.CreateDate < GETDATE() + 1)
GROUP BY
jD.AccountID,
COA.Name,
jD.Qty,
jD.CreateDate,
AttributeDefinitions.Name,
AttributeDefinitions.Description,
AttributeValues.Value
ORDER BY
jD.AccountID
) T
PIVOT
(
MAX([Name]) FOR Name IN (' + @Attributes + ')
) PT
'
EXEC(@SQL);