ASP.NET - Want sql Query ...Help Required... - Asked By Justin Deva on 05-Mar-12 02:04 AM

 

 want sql query to find sum of two diff columns from two diff tables and want to find their difference from thier sum...Help Required...
Web Star replied to Justin Deva on 05-Mar-12 02:16 AM
Just get sum on variable and subtract it as follows
Declare @sumA numeric(19,2)
Declare @sumB numeric(19,2) 
Declare @diff numeric(19,2) 



Select @sumA =Sum(colname1) sumA From tablname1
Select @sumB = Sum(colname2) sumB From tablname2 

Set @diff =  @sumA -@sumB



hope this helps you
Somesh Yadav replied to Justin Deva on 05-Mar-12 02:20 AM

This query will give the results you seem to want:

SELECT
   P
.InstitutionID,
   P
.AccountNumberKey,
   Total
= C.Value1 + C.Value2
FROM
   Parent P
   
INNER JOIN (
     
SELECT DISTINCT AccountNumberKey, Value1, Value2
     
FROM Child
   
) C ON P.AccountNumberKey = C.AccountNumberKey

But I want to echo what others have said: if you can do anything about the design, you should, because it is not normalized. Value1 and Value2 from your Child table really belong in the Parent table, as they are about the Parent. What if two rows in the Child table have a different set of Values for the same AccountNumberKey? Your data would be all wrong and who knows what sort of possibly disastrous consequences that could have for the business? The DISTINCT above would fail in this case and return two rows for the Parent row.