Hi @kasim mohamed
Here is a query based on what i commented above. Please check:
DECLARE @Column_Names VARCHAR(MAX)
DECLARE @SQL_String VARCHAR(MAX)
SELECT @Column_Names = ISNULL(@Column_Names + ',','') + QUOTENAME(Column_Names)
FROM (SELECT '_'+CAST(InvLevel AS VARCHAR(10))+Column_Name AS Column_Names
FROM ##ReInvoice CROSS APPLY(VALUES('ReInvDate'),('ReInvAmount'))C(Column_Name)
UNION
SELECT '_'+CAST(PayLevel AS VARCHAR(10))+Column_Name
FROM ##Payment CROSS APPLY(VALUES('PayDate'),('PayAmount'))C(Column_Name))S
ORDER BY Column_Names
--PRINT @Column_Names
SET @SQL_String = '
;WITH CTE1 AS
(
SELECT I.ID,I.InvDate,I.Amount,SUM(P.Amount) AS PaidAmount,I.Amount-SUM(P.Amount) AS Balance
FROM ##Invoice I JOIN ##Payment P ON I.ID=P.ID
GROUP BY I.ID,I.InvDate,I.Amount
),CTE2 AS
(
SELECT C.ID,C.InvDate,C.Amount,C.PaidAmount,C.Balance
,R.ReInvDate AS [DATE],''_''+CAST(R.InvLevel AS VARCHAR(20))+''ReInvDate'' AS [DATE_TAG]
,R.Amount AS [Amount_Value],''_''+CAST(R.InvLevel AS VARCHAR(20))+''ReInvAmount'' AS [Amount_TAG]
FROM CTE1 C JOIN ##ReInvoice R ON C.ID=R.ID
UNION ALL
SELECT C.ID,C.InvDate,C.Amount,C.PaidAmount,C.Balance
,P.PayDate AS [DATE],''_''+CAST(P.PayLevel AS VARCHAR(20))+''PayDate'' AS [DATE_TAG]
,P.Amount AS [Amount_Value],''_''+CAST(P.PayLevel AS VARCHAR(20))+''PayAmount'' AS [Amount_TAG]
FROM CTE1 C JOIN ##Payment P ON C.ID=P.ID
),CTE3 AS
(
SELECT ID,InvDate,Amount,PaidAmount,Balance,C.Column_Name,C.Column_Value
,CASE WHEN Amount=PaidAmount THEN ''Paid''
WHEN Amount>PaidAmount AND Balance > 0 THEN ''Partial''
ELSE ''Open'' END AS PaymentStatus
FROM CTE2 CROSS APPLY(VALUES([DATE_TAG],CAST([DATE]AS VARCHAR(20))),([Amount_TAG],CAST([Amount_Value]AS VARCHAR(20))))C(Column_Name,Column_Value)
)
SELECT *
FROM CTE3
PIVOT(MAX(Column_Value)FOR Column_Name IN('+@Column_Names+'))P
'
--PRINT (@SQL_String)
EXEC (@SQL_String)
Output:
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.