简体   繁体   English

mysql 查询每个组的 select 最大值,如果最大值大于该组的所有其他值

[英]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:我有一个名为 tab1 的表,如下所示:

id ID obj对象 col2 col2 val
1 1 obj1对象1 item1项目1 2 2
2 2 obj2对象2 item2项目2 5 5
3 3 obj1对象1 item3第 3 项 4 4
4 4 obj2对象2 item1项目1 5 5
5 5 obj3对象3 item4第 4 项 2 2
6 6 obj3对象3 item2项目2 1 1

How to find the row with the maximum value for each object in the obj column.如何找到obj列中每个object的最大值的行。 The maximum value of an object should be strictly greater than the other values of of the object. object 的最大值应严格大于 object 的其他值。

The output should be like this: output 应该是这样的:

id ID obj对象 col2 col2 val
3 3 obj1对象1 item3第 3 项 4 4
5 5 obj3对象3 item4第 4 项 2 2
SELECT id,obj,col2,max(val) 
FROM tab1
GROUP BY obj
id ID obj对象 col2 col2 val
3 3 obj1对象1 item3第 3 项 4 4
2 2 obj2对象2 item2项目2 5 5
5 5 obj3对象3 item4第 4 项 2 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)我尝试了这个查询,但 output 包括 obj2,其最大值不严格大于第二个最大值(obj2 的最大值和第二个最大值都是 5)

Using DENSE_RANK as mentioned by @Rick James.使用@Rick James 提到的DENSE_RANK

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.根据与单行对象相关的要求,调整子句x.cnt1

Refer fiddle here . 在这里参考小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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