Hi @Jonathan Brotto
It is a common question to get the output of at least two aggregate functions in the SQL pivot table columns.
Of course it is not possible to combine two different values resulting from two aggregate functions only in a single column.
Here are some solutions and samples that I can offer to you.
--test data
CREATE TABLE #TEST(ItemCode INT,[Year] INT,Quantity INT,LineTotal INT)
INSERT INTO #TEST VALUES(101,2019,111,1111),(102,2019,222,2222),(103,2020,333,1111),(101,2020,111,2222),(102,2021,222,1111),(103,2021,222,3333)
SELECT * FROM #TEST
--sample 1
SELECT * FROM ( SELECT 'Quantity SUM' AS ' ',ItemCode,Quantity,[Year] FROM #TEST ) S
PIVOT ( SUM(Quantity) FOR [Year] IN ( [2019],[2020],[2021] ) ) P
UNION ALL
SELECT * FROM ( SELECT 'LineTotal SUM' AS ' ',ItemCode,LineTotal,[Year] FROM #TEST ) S
PIVOT ( SUM(LineTotal) FOR [Year] IN ( [2019],[2020],[2021] ) ) P
And these two :
--sample 2
SELECT * From
(SELECT A.ItemCode,B.*
From #TEST A
CROSS APPLY ( VALUES (CAST([Year] AS VARCHAR)+' Quantity SUM', Quantity ) ,(CAST([Year] AS VARCHAR)+' LineTotal SUM',LineTotal) ) B (Item,Value)) A
PIVOT (SUM([Value]) For [Item] in ([2019 Quantity SUM], [2019 LineTotal SUM],[2020 Quantity SUM], [2020 LineTotal SUM],[2021 Quantity SUM], [2021 LineTotal SUM]) ) p
--sample 3
SELECT ItemCode,
SUM(CASE WHEN [Year]=2019 THEN Quantity END) AS [2019 Quantity SUM],
SUM(CASE WHEN [Year]=2019 THEN LineTotal END) AS [2019 LineTotal SUM],
SUM(CASE WHEN [Year]=2020 THEN Quantity END) AS [2020 Quantity SUM],
SUM(CASE WHEN [Year]=2020 THEN LineTotal END) AS [2020 LineTotal SUM],
SUM(CASE WHEN [Year]=2021 THEN Quantity END) AS [2021 Quantity SUM],
SUM(CASE WHEN [Year]=2021 THEN LineTotal END) AS [2021 LineTotal SUM]
FROM #TEST
GROUP BY ItemCode
Best regards,
LiHong