Hi @Mohamed Farook
Try this query:
;WITH CTE1 AS
(
SELECT cid
,CONVERT(VARCHAR(50),TYPE) type
,CONVERT(VARCHAR(50),description) description
,VALUE AS ledgers
,ROW_NUMBER()OVER(PARTITION BY cid,CONVERT(VARCHAR(50),TYPE) ORDER BY CONVERT(VARCHAR(50),ledgers)) RNum1
FROM #temp_table CROSS APPLY STRING_SPLIT(CONVERT(VARCHAR(50),ledgers),',')
),CTE2 AS
(
SELECT cid
,CONVERT(VARCHAR(50),TYPE) type
,CONVERT(VARCHAR(50),description) description
,VALUE AS ledger_id
,ROW_NUMBER()OVER(PARTITION BY cid,CONVERT(VARCHAR(50),TYPE) ORDER BY CONVERT(VARCHAR(50),ledgers)) RNum2
FROM #temp_table CROSS APPLY STRING_SPLIT(CONVERT(VARCHAR(50),ledger_id),',')
)
SELECT C1.cid,C1.type,C1.description,C1.ledgers,C2.ledger_id,SUM(T.Amount) Total_Amount
FROM CTE1 C1 LEFT JOIN CTE2 C2 ON C1.cid=C2.cid AND C1.type=C2.type AND C1.RNum1=C2.RNum2
JOIN #temp T ON C2.ledger_id=T.LedgerID
GROUP BY
GROUPING SETS ((C1.cid,C1.type,C1.description,C1.ledgers,C2.ledger_id)
,(C1.cid,C1.type)
)
Output:
Best regards,
Cosmog Hong
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".