Hi @Analyst_SQL
Not sure I understand right, but try this:
DECLARE @Level_Five_ID INT
SET @Level_Five_ID = 123100001
SELECT Trans_ID
,CASE WHEN Trans_Amount_D IS NULL
THEN (SELECT STRING_AGG(Level_Five_ID,' ') FROM #tbl_Transection_Test B WHERE A.Trans_ID =B.Trans_ID AND B.Trans_Amount_D IS NOT NULL)
WHEN Trans_Amount_C IS NULL
THEN (SELECT STRING_AGG(Level_Five_ID,' ') FROM #tbl_Transection_Test B WHERE A.Trans_ID =B.Trans_ID AND B.Trans_Amount_C IS NOT NULL)
END AS Level_Five_ID
,Trans_Date
,ISNULL(Trans_Amount_D,0) AS Trans_Amount_D
,ISNULL(Trans_Amount_C,0) AS Trans_Amount_C
,ISNULL(Trans_Amount_D,0) - ISNULL(Trans_Amount_C,0) AS Balance
FROM #tbl_Transection_Test A
WHERE Level_Five_ID = @Level_Five_ID
Note that STRING_AGG works in SQL Server 2017 (14.x) and later. For versions before 2017, an alternative method is using Stuff
function along with for xml path
.
Best regards,
Cosmog
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".