Suppose I have a user’s count of visit for each countries:
The query goes:
SELECT
countries_users.user_id,
countries.name,
count(countries_users.id) as count_visit
FROM countries_users
LEFT JOIN countries on countries.id = countries_users.user_id
WHERE countries_users.user_id IN (111, ...)
GROUP BY countries_user.user_id, countries.id
The result would be:
user_id | countries | count_visit
-------------------------------
111 | Norway | 5
111 | Japan | 2
... | ... | ...
Now, normally, I would’ve done this on the code-level, However, for some stupid reason , I would like to append additional column to the result set, and that column is the total count_visit of the user regardless of the country.
So, instead of the result above, it will now be:
user_id | countries | count_visit | overall_visit
---------------------------------------------------
111 | Norway | 5 | 7
111 | Japan | 2 | 7
... | ... | ... | ...
3
Answers
may you need a subquery
Test this:
You’d obtain something like
Use
SUM OVER
to add up the user’s visit counts.I’ve amended the join condition – you’ll want to join countries on the country ID not the user ID.
And I turned the join into an inner join, because why would a countries_users row without a country even exist? If you do want users without any visits, then use the users table: