I'm trying to slog my way through your tables and queries, but it's very confusing. First, could you please go back and Modify your post to 1) add spaces to make columns line up, and 2) break up the SQL queries into multiple lines, so we don't have to scroll left and right all over the place? Thanks.
Next, your tables are very poorly structured. You have lots of redundant data, which wastes space and introduces the risk of having inconsistent data. First, I would have an agent table:
agentMLSID, FirstName, LastName, OfficeID
I'm assuming that the OfficeID doesn't change all that often. If it does, you could keep the OfficeID with the selling_history or teams table.
I don't know if the teams change membership, or are fairly fixed. If they're fixed, they can have a teams table:
teamID, teamName, leaderID
and a teamMembers table listing who's in the team:
teamID, agentMLSID
If team membership is fairly fluid, you'd need to do something else.
Then your selling_history table becomes
id, agentMLSID, MLSID, price, date
I take it the MLSID is the ID of the sale (transaction) itself? What then is "id"? If a given
team handles the sale, you then have only one row per sale, and your problem goes away (replace agentMLSID by teamID).
From your question, I'm guessing that multiple agents, on a team, can participate in a sale, but you only want to count the value of a sale once for a team, not once for each team
member (agent)? In "next query", "total" is just a placeholder until the next step? It doesn't seem to mean anything in that context, although it may give a clue as to what's going wrong. As I said above, crediting a sale to a
team would leave you with only one row per sale, which should clear up the problem (plus, eliminate redundant data for price and date). If team membership is very fluid, are you willing to create new "teams" for every combination of agents that makes a sale?