Question : Using Pivot with Dynamic Columns and a Group By

I have the following:

DECLARE @listCol VARCHAR(2000)
SELECT  @listCol = STUFF((SELECT DISTINCT
'],[' + Description
FROM    Items
ORDER BY '],[' + Description FOR XML PATH('')), 1, 2, '') + ']'
DECLARE @query NVARCHAR(4000)
SET @query = 'SELECT CustReference,'+@listCol+' FROM assets
PIVOT( SUM(AssetQTY) FOR AssetType IN ('+@listCol+')) AS p group by CustReference
EXECUTE(@query)

This basically determines the column names and stores them in @listCol, I want to group by CustReference. So to achieve this I need an Aggregate function around '+@listCol+' but this fails as the aggregate functions require 1 argument.

Any ideas how to get this working?

Answer : Using Pivot with Dynamic Columns and a Group By

I never saw the reference to OrderID until the last comment.
Here you go


DECLARE @listCol VARCHAR(2000)
SELECT  @listCol = STUFF((SELECT DISTINCT
'],[' + Description
FROM    Items
ORDER BY '],[' + Description FOR XML PATH('')), 1, 2, '') + ']'
DECLARE @query NVARCHAR(4000)
SET @query = 'SELECT orderid,CustReference,'+@listCol+' FROM
(select orderid, CustReference, AssetType, Sum(AssetQty) as AssetQty
FROM assets group by orderid, CustReference, AssetType) X
PIVOT( SUM(AssetQTY) FOR AssetType IN ('+@listCol+')) AS p '
EXECUTE(@query)
Random Solutions  
 
programming4us programming4us