I have two tables, users and sales. I want to be able to get the sum of all profits made by each user.
Users
_ _ _ _ _ _ _ _ _ _
|id |
|first_name |
|second_name |
| |
| |
| |
| |
_ _ _ _ _ _ _ _ _ _
Sales
_ _ _ _ _ _ _ _ _ _
|id |
|user |
|profit |
| |
| |
| |
| |
_ _ _ _ _ _ _ _ _ _
One option uses a correlated subquery:
select u.*,
(select sum(s.profit) from sales s where s.user = u.id) as total_sales
from users u