I’ve successfully merged 3 tables (using ID’s), but when I try to add 4th table – output completely messes up (values become unrealistic/wrong) so I think that I has something to do with the fact, that this 4th table has ungrouped ID’s, so I need to group them before Joining this new table. Right now the query is following:
SELECT name, SUM(money) AS MONEY
FROM transactions
JOIN results ON transactions.id = results.id
JOIN more ON results.per_id = more.per_id
GROUP BY name
HAVING SUM(money)>500
and when I join new table:
SELECT name, SUM(money) AS MONEY, SUM(data_from_NT1), SUM(data_from_NT2)
FROM transactions
JOIN results ON transactions.id = results.id
JOIN more ON results.per_id = more.per_id
JOIN newtable ON results.per_id = newtable.per_id
GROUP BY name
HAVING SUM(money)>500
is it possible to execute a command GROUP BY per_id:
(JOIN newtable ON results.per_id = newtable.per_id GROUP BY per_id)
before adding this new table into the main table? The line from above doesn’t work.
Yes, it is possible, but you have to write it as a SELECT. This is a first version of a possible answer:
It isn’t completely clear whether you need the ‘SUM of SUMs’ in the main select-list; you probably don’t. It also isn’t clear where the
nameormoneycolumns come from; I’d normally prefix them with the appropriate table alias, too. With those caveats, this might be more nearly what you’re after:There are undoubtedly other ways to write this. The grouping in the main query might be better put into a parallel sub-query, leaving simple direct joins in the main query. But we don’t have the information to actually do that for you.