Retrieve TOP X members of each group using SQL Server 2005 -


I have seen that this question has been asked many times, and I have written my query, but it is very slow,

In a simple scenario, I have the following two tables:

Group
- Group ID (primary key) Member member (key key)
Group ID (foreign key )

Suppose, for each groupID in the group, I have to find the top two member item values ​​from the member group that is groupID.

This is my current query that works, but the pain is slow:

  SELECT M.MemberID, M.GroupID FROM member AS M WHERE in M.MemberID ( Select the top 2 members.See member member member member IDID = M. Group ID order by member. MIBIDID)  

The following lines are in the group:
Group ID 1
2
3

And the member has the following lines
MemberEid, GroupID
1, 1
2, 2
3, 3
4 , 1
5, 2
6, 3
7, 1
8, 2
9, 3

Then my query should be returned:
MemberEid GroupID
1, 1
2, 2
3, 3
4, 1
5, 2 < 6, 3

I believe that the dependent nested query is well for the DB engine Can be optimized (although requested by John Saunders to see that the execution plan is well established, and by looking at what index you do not have - -).

However, in SQL Server 2005 and 2008 a more natural approach to ranking issues of this kind is the SQL engine, because the feature is in recent ANSI standards) Ranking function - rank , DENSE_RANK , or ROW_NUMBER ... are all equivalent when you are ranking by a unique area ;-) Apart from optimization, Can be read easily after use (and And more powerful when your problems are more difficult than this), especially with the help of that other clean new -heart construction, with paragraph ...:

  

Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -