Jump to content

GROUP BY but limit to top 2 per group


johnsmith153

Recommended Posts

Number of items sold in a transaction

 

Department / Customer / SalesPersonID / Sales

 

A / Mr Smith / 1 / 3

A / Mr Brown / 2 / 2

A / Mr Roberts / 1 / 5

A / Mrs Smith / 2 / 1

A / Mr Andrews / 2 / 1

A / Mrs Black / 3 / 2

B / Mr Smith / 1 / 1

etc.

(there will be many departments)

 

SELECT Department, SalesPersonID, totSales FROM $table GROUP BY Department, SalesPersonID ORDER BY SUM(Sales) AS totSales

 

This will group and return them all, but I only want the TOP 2 per department

 

Link to comment
Share on other sites

The "simplest" method is to keep a user-defined variable, which you reset per "group", and simply filter out the rows once you've hit your "limit" -- 2.

 

Of course, by "simplest " I mean easiest to type, not most efficient.  If you want the latter, you'll need to forgo examining each record, and use an derived table to get the N-most per group (and dealing with the edge case of there not being N rows), and then join that up the chain.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.