I've seen this question asked a couple of times, and I've written my own query, but it's quite slow, and I would be extremely grateful if someone could offer advice on how to speed it up.
In a simplified scenario, I have the following two tables:
Group
- GroupID (primary key)
Member
- MemberID (primary key)
- GroupID (foreign key)
Let's say, for each GroupID in Group, I want to find the top 2 MemberID values from Member that have that GroupID.
Here's my current query that works, but is painfully slow:
SELECT M.MemberID, M.GroupID
FROM Member AS M
WHERE M.MemberID in
(Select top 2 Member.MemberID
FROM Member
Where Member.GroupID = M.GroupID
ORDER BY Member.MemberID)
Say Group has the following rows
GroupID
1
2
3
and Member has the following rows
MemberID, GroupID
1, 1
2, 2
3, 3
4, 1
5, 2
6, 3
7, 1
8, 2
9, 3
Then my query should return:
MemberID GroupID
1, 1
2, 2
3, 3
4, 1
5, 2
6, 3