Can anyone help me by showing a create procedure statement for calculating Total Dues from three tables? Here are the tables along with their data ..
Table_1
accountno shipername shiperaddress Executivename
001 john 123, London Paul
002 Robi 127, China Soma
Table_2
Executivename shipername shiperaddress accountno currentamount anotheramount
paul john 123,london 001 10500 12000
soma robi 127,china 002 11000 6800
Table_3
accountno Date ReceivedAmount MoneyReceiptNo
001 1/1/2012 6500 G 256412
002 1/2/2012 5200 D 246521
Here I am to mention that the Total Dues will be calculated as
(currentamount + anotheramount) - receivedamount
I tried to do that by the following stored procedure.
CREATE PROCEDURE [dbo].[rptexetotaldues] @Executivename varchar(20)
AS BEGIN
select
table_1.Executivename,
sum(table_2.currentamount + table_2.anotheramount
- table_3.receivedamount ) as TotalDues
from
table_1
full join
table_2 on table_1.accountno = table_2.accountno
join
table_3 on table_3.accountno = table_1.accountno
where
table_1.Executivename = @Executivename
group by
table_1.Executivename
end
But that doesn't work. Please somebody help me.
I can think of two problems. First is that the account number is duplicated in either table 1 or table 2. This will add extra rows.
The second is that there are rows in table three that are not in table 2. This means that the addition within the sum is NULL because one of the values is NULL. You can fix this in one of these ways:
or
Your sample worked for me. The only thing I changed is "Date" to transdate. I strongly recommend avoiding "Date" as a column name. I also changed the aliasing a bit, but that should have been allright. I thinkg @Gordon Linoff is right - you could have an issue with NULLS.
Here are my results:
I think it would be more straightforward as a UNION query, example below: