Nie ma potrzeby dwukrotnego obracania.
Przykład
Declare @SQL varchar(max) = '
Select *
From (
Select A.Account
,B.*
From (Select Account
,ProductID
,Qty = sum(Qty)
,RN=Row_Number() over (Partition By Account Order by ProductID)
From YourTable
Group By Account,Productid
) A
Cross Apply (values (''qty''+cast(RN as varchar(25)),cast(Qty as varchar(100)))
,(''product''+cast(RN as varchar(25)),cast(productid as varchar(100)))
) B (Item,Value)
) A
Pivot (max([Value]) For [Item] in (' + Stuff((Select Distinct ','+QuoteName('product'+ColNr)
+','+QuoteName('qty'+ColNr)
From (Select Distinct ColNr=cast(Row_Number() over (Partition By Account,ProductID Order by (Select NULL)) as varchar(25)) From YourTable ) A
Order By 1
For XML Path('')),1,1,'') + ') ) p'
Exec(@SQL);
Print @SQL
Zwroty
Jeśli to pomaga w wizualizacji — podzapytanie generuje