-
CosmogHong-MSFT 9,086 Reputation points Microsoft Vendor
2022-08-18T08:48:21.147+00:00 Hi @Shahab a
For report1, try this:;WITH CTE AS ( SELECT ID,Rows,[DESC],Debit,Credit,C.* FROM VoucheItem CROSS APPLY(VALUES(AdRef1,'AdRef1'), (AdRef2,'AdRef2'), (AdRef3,'AdRef3'), (AdRef4,'AdRef4'))C(AdRef_Value,AdRef_Type) ) SELECT ADId,ADDetail,[DESC],Debit,Credit,SUM(Debit-Credit)OVER(PARTITION BY ADId,ADDetail ORDER BY [DESC] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS Result FROM AccountDetail A JOIN CTE C ON A.ADId=C.AdRef_Value WHERE ADId=4000
For report2, check this:
;WITH CTE AS ( SELECT ID,Rows,[DESC],Debit,Credit,C.* FROM VoucheItem CROSS APPLY(VALUES(AdRef1,'AdRef1'), (AdRef2,'AdRef2'), (AdRef3,'AdRef3'), (AdRef4,'AdRef4'))C(AdRef_Value,AdRef_Type) ) SELECT ADId,ADDetail,SUM(Debit)Debit,SUM(Credit)Credit,SUM(Debit)-SUM(Credit)AS Result FROM AccountDetail A JOIN CTE C ON A.ADId=C.AdRef_Value WHERE ADId=4000 GROUP BY ADId,ADDetail
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.
How to join 2 tables with different records in columns

Shahab a
201
Reputation points
I have 2 tables
That name is:
AccountDetail and VoucheItem
table AccountDetail has records as follows
table VoucheItem has records as follows
Now I want to get report from code 4000 which is stored in two different columns using join.
how to do it
{count} votes
Accepted answer