Forum Discussion
BADDULA
May 26, 2025Copper Contributor
Sql Query
Hi All, I have a requirement. want output data like below screen print CREATE TABLE [dbo].[Source_Table]( [Product] [varchar](10) NULL, [Trans_type] [varchar](10) NULL, [Sa...
rodgerkong
May 28, 2025Iron Contributor
If my understanding is correct, the value of Profitamont in the first line of the output should be 20.
To get the result you want, needs 3 steps:
- Aggredated [SalesCode] by [Product] and [Trans_type].
- Transform the values of [Trans_type] to columns by using PIVOT.
- Summary the [Profitamount] by [Product] and JOIN the rowset with the rowset which returns by PIVOT.
Code
;
WITH CTE([Product], [Trans_type], [Codes], [Profitamount])
AS
(
SELECT [Product], [Trans_type], STRING_AGG([SalesCode], ',') AS Codes, SUM([Profitamount]) AS [Profitamount]
FROM [Source_Table]
GROUP BY [Product], [Trans_type]
),
P([Product], [sales_type1], [sales_type2])
AS
(
SELECT [Product], [Type1], [Type2] FROM
(
SELECT [Product], [Trans_type], [Codes] FROM CTE
) AS S
PIVOT
(
MIN([Codes]) FOR [Trans_type] IN ([Type1], [Type2])
)AS PV
)
SELECT P.*, T.[Profitamount] FROM P LEFT JOIN
(
SELECT [Product], SUM([Profitamount]) AS [Profitamount] FROM CTE
GROUP BY [Product]
)T ON P.[Product] = T.[Product]