Jump to content

Problem using LIMIT on groups of data


Buchead

Recommended Posts

Hello all,

 

I have 1 table I'm having trouble pulling the required data from in 1 query, and simply wonder if it's not possible and should be split into 2 part:

 

table:

userTasks

 

fields:

taskID

userID

year

taskNumber

 

What I'm attempting to do is pull out the top 5 tasks for each user in a given year. As the table will contain multiple year's data (the taskNumber restarts at 1 for each year), is it possible to pull out the top 5 from each year in one query?

 

I'd thought of:

 

SELECT * FROM `userTasks` WHERE `userID`='1' ORDER BY `year` ASC, `taskNumber` ASC LIMIT 5

 

but that, as expected, only pulled out the very 5 top records. Adding in a GROUP BY `year` command didn't work.

 

 

A solution I have working is to 1st query the table and pull out all the individual `year` numbers and then cycle through that array pulling out the data. Just wondering if I could save the trouble and use only 1 query.

 

Thanks for any assistance,

 

Clive.

Link to comment
Share on other sites

The problem is that you can't group by in the "middle" of a join... or LIMIT a join.

 

One way to do this would be to use user variable to assign a value of 1 to the first 5 from each year, and then a 0 for the remaining ones -- and then filter with HAVING magicField = 1.

Link to comment
Share on other sites

Here is a preliminary :

 

SELECT ut1.userID
      ,ut1.taskNumber
      ,ut1.`year`
      ,COUNT(*) as 'count'
FROM userTasks ut1
JOIN userTasks ut2 ON ut1.userID = ut2.userID AND ut1.`year` < ut2.`year`
GROUP BY ut1.userID, ut1.`year`, ut1.taskNumber
HAVING `count` <= 5
ORDER BY userID DESC, `year` DESC

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.