In SQL I'm trying to combine multiple tables and grab the SUM of expenses per person, and sort those by highest total expense first. I have 3 tables:
- test1 (from grocery store #1)
- test2 (from grocery store #2),
- junction1 (one that I just created to somehow try to connect test1 and test2 together)
I cannot edit test1 and test2 in the production environment. I created junction1 as a bridge to connect test1 and test2. I can modify columns/content in junction1. The IDs of test1 and test2 may change in the future (right now they are the same).
Desired result:
I need to do a full join on all tables, since I want to include all personnel from both tables. test1 and test2 are independent, as some people only shop in test1 locations and some only shop in test2 locations. Also to sort by Total SUM of both tables I tried:
ORDER BY SUM(Grocery1 + Grocery2) DESC
No luck.
A SUM select statement (no joins) works:
select junction1.Name1, SUM(Amount) AS Grocery1
from test1
FULL JOIN junction1 on junction1.ID1= test1.ID1
GROUP BY junction1.Name1 ORDER BY Grocery1 DESC;
But when I join the table(s):
select junction1.Name1, SUM(test1.Amount) AS Grocery1, SUM(test2.Amount) AS Grocery2
from test1
FULL JOIN junction1 ON test1.ID1 = junction1.ID1
FULL JOIN test2 ON test2.ID2 = junction1.ID2
GROUP BY junction1.Name1
It gives:
The data is off in both columns. Andy should only have $400 for Grocery1. It looks like it's multiplying it instead of adding it. I tried to divide by 3, which helps some of the people with 3 entries, but that's probably not what I want.