This topic is locked

select max() and 2nd highest

5/20/2008 2:56:43 PM
PHPRunner General questions
V
vytb author

Is there a solution to select not only max() and min() but the second, third highest value as well in the mysql query?
Sorry for posting the question only partly belonging to the PHPR, but still...

S
steveh 5/21/2008

Yes but in a messy way, something along the lines of:-
select max(a),b

from mytable,(select max(a) maxa,b from mytable group by <img src='https://asprunner.com/forums/file.php?topicimage=1&fieldname=reply&id=29501&image=1&table=forumreplies' class='bbc_emoticon' alt='B)' /> z

where mytable.a<z.maxa and mytable.b=z.b

group by b

V
vytb author 5/22/2008

Yes but in a messy way, something along the lines of:-

select max(a),b

from mytable,(select max(a) maxa,b from mytable group by <img src='https://asprunner.com/forums/file.php?topicimage=1&fieldname=reply&id=29609&image=1&table=forumreplies' class='bbc_emoticon' alt='B)' /> z

where mytable.a<z.maxa and mytable.b=z.b

group by b


Thanks a lot, it indeed appears to be what I need. Could you precise for the following situation:
I've got the groups of variables according to the indeterminate number of dates with indeterminate datediff (let say a1, a2, a2 for the dates d1, d2, d3...). I would like joining table with itself (alias) in order to have a table like
a1 d1 a2 d2 a3 d3 ...
I see no other way but to select variables a1 where d1 = min(d), a2 where d1<d2 and d2>d3, etc.
Still, I would like to limit the number of the dates to the realistic one, say 10 where d10 =max(d)

S
steveh 5/23/2008

Just keep extending the above, but you'll get to the point where there are so many subselects that if you've a lot of data then you'll have an issue.
Depending on your database and the number that you have, you may be better selecting the keys then selecting top 10 x from mytable where y=nnn order by x desc

V
vytb author 5/23/2008

Just keep extending the above, but you'll get to the point where there are so many subselects that if you've a lot of data then you'll have an issue.

Depending on your database and the number that you have, you may be better selecting the keys then selecting top 10 x from mytable where y=nnn order by x desc


Not sure if I get you...
Sure I would like to select the keys (one by one) but the top 10 I will get only for all the table (limit, etc.)...
Lets see, I have parenttable with primary id= ID

child table on ID with primary autoincremental subId
every ID has a different nb of subId. I need to group those subId's (with belonging variables) horizontally for each ID.