14,982,169 members
5.00/5 (1 vote)
See more:
i have created a view to join three tables SUMDEPOSITES,SUMWITHDRAWALS and SUMLOANS
In SUMDEPOSITES i have
SQL
```SELECT DISTINCT AccountNumber, SUM(Amount) AS deposites
FROM         dbo.DepositeDetails
GROUP BY AccountNumber```

in SUMWITHDRAWALS i have
SQL
```SELECT DISTINCT AccountNumber, SUM(Amount) AS withdrawals
FROM         dbo.WithdrawalDetails
GROUP BY AccountNumber```

in SUMLOANS i have
SQL
```SELECT DISTINCT AccountNumber, SUM(TotRepayment) AS Loans
FROM         dbo.Loans
GROUP BY AccountNumber```

now i have created a third view BALANCE which is to do this calculation
SQL
```SELECT     dbo.SUMDEPOSITES.AccountNumber, dbo.SUMDEPOSITES.deposites - dbo.SUMWITHDRAWALS.withdrawals - dbo.SUMLOANS.Loans AS Balance
FROM         dbo.SUMDEPOSITES LEFT OUTER JOIN
dbo.SUMWITHDRAWALS ON dbo.SUMWITHDRAWALS.AccountNumber = dbo.SUMDEPOSITES.AccountNumber LEFT OUTER JOIN
dbo.SUMLOANS ON dbo.SUMLOANS.AccountNumber = dbo.SUMWITHDRAWALS.AccountNumber```

But the problem is when there is no data in SUMDEPOSITES or SUMLOANS and there is data in SUMDEPOSITES, it rturns null instead of the data in SUMDEPOSITES.
When on table is empty i do not get a correct answer.
Can someone help me?
Posted
Updated 19-Jan-13 1:41am
v2

Solution 2

This query depend on the scenario. If this is banking application here is my idea.
You have three view for DEPOSITS, WITHDRAWALS, and LOANS
In normal scenario, you can't withdraw money without deposit (correct me if I'm wrong).
account number for both (Deposits and withdrawals) are same.
that mean for joining clause for DEPOSITS and WITHDRAWALS is `LEFT OUTER JOIN`.
But for the LOAN, accounts, account numbers are not same. you have to JOIN using `UNION`

This is just for a idea. correct me if i'm wrong.
v2
wizy@2020 19-Jan-13 17:53pm

You are right just that LOAN account numbers are also the same as deposites and withdrawals
wizy@2020 19-Jan-13 17:53pm

so what do i do then? Tharaka MTR
Tharaka MTR 19-Jan-13 21:33pm

If you are using same account no for DEPOSITS and LOANS. then above answer is correct. you have to use ISNULL to validate the fields.

That's why we need some background information of the question before answering. In real world, banking application if you open the Deposit account and Loan account you will get the two different account numbers.

Solution 1

Hi,

The problem occurs due to NULL values in Table and you are doing calculation on that.
so try your query following way.

SQL
```SELECT     dbo.SUMDEPOSITES.AccountNumber, isnull(dbo.SUMDEPOSITES.deposites,0) -
isnull(dbo.SUMWITHDRAWALS.withdrawals,0) - isnull(dbo.SUMLOANS.Loans,0) AS Balance
FROM         dbo.SUMDEPOSITES LEFT OUTER JOIN
dbo.SUMWITHDRAWALS ON dbo.SUMWITHDRAWALS.AccountNumber = dbo.SUMDEPOSITES.AccountNumber LEFT OUTER JOIN
dbo.SUMLOANS ON dbo.SUMLOANS.AccountNumber = dbo.SUMWITHDRAWALS.AccountNumber```