Hi @JM12377
This works correctly for the PhaseId /Unit sum - but I'd also like a PhaseId/Amount Sum.
When using PIVOT, we can only aggregate one column at a time. If you want to SUM multiple columns, you could use UNPIVOT or CROSS APPLY to integrate the columns that you want to SUM into the same columns, and add a new column to identify these datas.
For example, from this to this
Then you could do PIVOT based on this modified dataset.
Since you didn't post the result you want, here are two possible queries you may refer to:
--query1: Using CROSS APPLY
SELECT elementid,Column_Name,[1] AS phaseid1,[5] AS phaseid5,[6] AS phaseid6
FROM
(
SELECT elementid,phaseid,C.*
FROM temp CROSS APPLY(VALUES(Units,'Units'),(amount,'Amount'))C(Column_Value,Column_Name)
)x
PIVOT (SUM(Column_Value) FOR phaseid in([1], [5], [6])) p
ORDER BY elementid
Output1:
--query2: Using UNPIVOT
SELECT * FROM
(
SELECT elementid
,'Phaseid'+CAST(phaseid AS VARCHAR(20))+'_'+Column_Name AS Column_Name
,C.Column_Value
FROM temp
UNPIVOT(Column_Value FOR Column_Name IN(Units,amount))C
)x
PIVOT (SUM(Column_Value) FOR Column_Name in([Phaseid1_units],[Phaseid1_Amount],[Phaseid5_units],[Phaseid5_Amount],[Phaseid6_units],[Phaseid6_Amount])) p
ORDER BY elementid
Output2:
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.