PDA

View Full Version : join یک جدول self referencing با یک جدول دیگر و جمع چند فیلد



gama_slv
یک شنبه 27 فروردین 1396, 11:22 صبح
برای جدول حساب ها از یک جدول self referencing استفاده کردم AccountId,ParentId,NameAccount,LevelAcc
و ریز سند حساب داری رو هم در جدول دیگه AccountId,Debtor,Creditor
در حسابداری برای بدست آوردن تراز آزمایشی در هر سطح از حساب LevelAcc باید جمع ستون بدهکار و بستانکار به علاوه جمع سطح های پایین تر رو داشته باشیم

برای این کار

WITH MyTest as
(
SELECT a.AccountId,a.ParentId ,a.NameAccount,cast(dbo.Statements.Debtor as int) AS SDeb, cast (dbo.Statements.Creditor as int) AS SCre
FROM dbo.Accounts a
INNER JOIN dbo.Statements ON a.AccountId = dbo.Statements.AccountId

UNION ALL
SELECT a1.AccountId, a1.ParentId,a1.NameAccount, cast( dbo.Statements.Debtor as int) + M.SDeb, cast (dbo.Statements.Creditor as int ) + M.SCre
FROM Accounts a1
INNER JOIN dbo.Statements ON a1.AccountId = dbo.Statements.AccountId
INNER JOIN MyTest M
ON M.AccountId = a1.ParentID

)
SELECT sum(SDeb),sum(SCre) From MyTest
group by ParentId
where LevelAcc=4

اما این خیلی درست نیست اگر بقیه قیلد ها رو بیارم دیگه سطح 4 به علاوه سطح 5 نمیکنه و کلا تمام سطح ها رو نمیشه بدست اورد