SQL Sum() with correlated subquery
-
28-10-2019 - |
Question
I have two tables: fund and items. Items has a field called fundID that is related to the ID of the fund table. Items also has a price field.
Here's a simplified example of the two tables:
FUND
ID fundName
1 maintenance
2 books
3 development
4 media
ITEMS
ID price fundID
1 $10 2
2 $20 4
3 $5 4
4 $8 1
5 $10 3
6 $12 4
I want to create a query that will give me the name of each fund and the sum of all prices for items that are connected to that fund through the fundID field. I have tried several methods such as having a correlated subquery within the SUM() and also within the WHERE, and I am getting errors.
If someone could point me in the right direction, I'd appreciate it.
Solution
Try this :
SELECT f.fundname,
SUM(i.price)
FROM fund f
JOIN items i
ON i.fundid = f.id
GROUP BY f.fundname
OTHER TIPS
There's no good reason to do it this way given your table structure however the question does ask about a sub query and the table structure is simplified.
So this will give the same results as straightfoward JOIN/GROUP BY
SELECT f.fundname,
coalesce(i.price,0) price
FROM fund f
LEFT JOIN (SELECT fundid,
SUM(price) price
FROM items i
GROUP BY fundid) i
ON f.fundid = i.fundid
Note the COALESCE/LEFT JOIN is there in case you want 0 for funds that have no items.
Try this
select fundName,sum(price) as TotPrice
from Funds f
join Items g on g.id=f.id
group by f.fundName
SELECT f.fundid, f.fundName, SUM(price)
FROM Fund f
INNER JOIN ITEMS i ON i.fundId = f.fundId
GROUP BY f.FUNDID
If you have a lot of funds fund Id is probably better to group by