views:

42

answers:

3

My table structure is (id,cluster,qid,priority). I'm trying to figure out how I can display the maximum value of priority for each cluster. Say cluster 1 has priorities 100, 102, 105. I want to display the record containing 105. Please help.

+1  A: 

Here is an article that explains how to select the row with the max value for each group.

http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

Wolfgang
thanks! this works!
1s2a3n4j5e6e7v
+2  A: 
select cluster, MAX(priority) from structure group by cluster;

To find all the columns TRY

select *  from structure
where priority = (
                select MAX(priority) from structure as s 
                where s.cluster = structure.cluster
              );
Salil
no, this won't work. It does not return the record with max priority for the cluster. just displays the max value.
1s2a3n4j5e6e7v
Ok try then my edited answer.
Salil
+1  A: 

You could filter out the rows with an inner join, like:

select  s.*
from    structure s
join    (
        select  cluster, MAX(priority) maxprio
        from    structure 
        group by 
                cluster
        ) filter
on      s.cluster = filter.cluster
        and s.priority = filter.maxprio

This would return multiple rows if they all have the maximum priority for that cluster.

Andomar
This works! Thanks for your immediate help. This seems to be a little slow compared to the logic http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ . Try checking it out if you wish.
1s2a3n4j5e6e7v