Skip to content
Advertisement

SQL SUM on multiple INNER JOIN

I am trying to get the sum of particular fields through multiple table using joins. I am getting the SUM wrong when I I try to get the values together.

I have table State as

I have another table Balance as

I have one more table Loan as

What I want as a result from my query is,

When I try to use the following query I am getting the sum for loan with state correctly,

I get the following result,

Similarly I can get the sum from the Balance Table. What I am trying to achieve is to get the sum form both the tables using a single transaction.

Although, I am able to get the desired values, if I do something like this,

However this is not very feasible on the large data set that I have. I tried,

But this gives me values as multiple of the actual value. It is actually the multiple of number of rows present in the child tables.

I am not asking for an exact solution, but any kind of pointers would be nice.

Advertisement

Answer

Do the aggregation for each table in a separate sub-query, then join:

(LEFT JOINs just in case a state has no loan or balance rows.)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement