Jump to content

Query help: Second best in each group?


Infinitive

Recommended Posts

I don't normally need SQL help but this one's a bit beyond me and I'm hoping someone knows a trick.

 

I have a table which can have users on it several times, along with scores, and I need to find everyone who's been on there at least twice along with how many times they appear and their second-highest score.  And it's that underlined bit that's the problem.  Consider some sample data:

Scores_Table:
ListingID	User	Version	Score
1		Adam	1	500
2		Adam	2	600
3		Adam	3	700
4		Barry	1	525
5		Barry	2	625
6		Carla	1	550
7		Doug	1	575
7		Doug	2	675

And the goal would be to return

User	Appearances	Second High
Adam	3		600
Barry	2		525
Doug	2		575

 

So I start with

SELECT User, Count(ListingID) as Appearances
FROM Scores_Table
GROUP BY User
HAVING Appearances >= 2

Which is sufficient to get the number of appearances but not the second highest score.  Min works for exactly two but not for three or more appearances.  The usual technique for second highest on a table won't work unless I want to run it for every user (which is my fallback plan).

 

So I'm hoping someone has a trick.  Help appreciated, thanks.

Link to comment
Share on other sites

  • 2 weeks later...
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.