Being quite new to SQL I'm struggling with a query.
My database contains the columns ID, WEIGHT, TEAM
I want to return the results of the top 3 WEIGHTS per ID, SUM them together and group by TEAM. Every other entry for ID would be ignored. So the results would read TEAM WEIGHT.
SELECT id, team, SUM( weight ) AS total
FROM (
SELECT id, team, weight
FROM database m
WHERE (
SELECT COUNT( * )
FROM database mT
WHERE
mT.id = m.id
AND mT.weight >= m.weight
) <=3
)tmp
GROUP BY team
ORDER BY total DESC
This is my effort but its definitely not right. Sorry if this is a basic query but I have researched online with no joy. I would appreciate any help as I'm a little stuck.
Table
ID Weight Team
1 100 A
5 200 C *
1 300 A *
1 100 A
3 50
1 200 A *
5 20 C
1 150 A *
5 200 C *
4 50 B *
5 200 C *
6 100 A *
2 50 C
6 100 A *
2 100 C *
6 100 A *
2 100 C *
6 50 A
2 200 C *
The expected results would be:
Team Total
C 1000
A 950
B 50
I have starred the values that should be summed (top 3 per ID grouped by Team). A point to note is that it's not the top 6 per team. It has to be the top 3 per ID added together, then the top 3 of different IDs added again to make the team total.