简体   繁体   中英

mysql query to select max value of each group if the maximum value is greater than all the other values of the group

I have a table named tab1 like this:

id obj col2 val
1 obj1 item1 2
2 obj2 item2 5
3 obj1 item3 4
4 obj2 item1 5
5 obj3 item4 2
6 obj3 item2 1

How to find the row with the maximum value for each object in the obj column. The maximum value of an object should be strictly greater than the other values of of the object.

The output should be like this:

id obj col2 val
3 obj1 item3 4
5 obj3 item4 2
SELECT id,obj,col2,max(val) 
FROM tab1
GROUP BY obj
id obj col2 val
3 obj1 item3 4
2 obj2 item2 5
5 obj3 item4 2

I tried this query but the output includes the obj2 whose max value isn't strictly greater than the second max value (both the max and the second max value of obj2 is 5)

Using DENSE_RANK as mentioned by @Rick James.

select id, obj, col2, val,cnt from (
   select *, 
   dense_rank() over (partition by obj order by val) rn,
   count(val) over (partition by obj,val) cnt,
   count(val) over (partition by obj) cnt1
   from max_tab) X
where
X.rn <> 1
AND X.cnt = 1
OR X.cnt1 = 1;

Adjust the clause x.cnt1 , as per requirements related to objects with single row.

Refer fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM