如何找到列差值最大的行对(按某列值分组)

我有一个类似于以下的表格,

如何找到列差值最大的行对(按某列值分组)

我想找到每个会话的性能差异最大的一对中心。所以,我想要一个如下表,

如何找到列差值最大的行对(按某列值分组)

我正在努力为h2数据库形成正确的查询。

gn666 回答:如何找到列差值最大的行对(按某列值分组)

您可以自联接表并使用相关的子查询进行过滤:

select 
    t1.session,t1.center center1,t2.center center2,t1.performance - t2.performance performance
from mytable t1
inner join mytable t2 on t1.session = t2.session
where t1.performance - t2.performance = (
    select max(t11.performance - t22.performance)
    from mytable t11
    inner join mytable t22 on t11.session = t22.session
    where t11.session = t1.session
)

或者您可以使用窗口功能:

select *
from (
    select 
        t1.session,t1.performance - t2.performance performance,rank() over(partition by t1.session order by t1.performance - t2.performance desc)rn
    from mytable t1
    inner join mytable t2 on t1.session = t2.session
) t
where rn = 1
,

H2可能有点棘手。我认为这可以满足您的要求:

select t.session,max(case when performance = min_performance then center end) as center_1,max(case when performance = max_performance then center end) as center_2,(max_performance - min_performance) as performance_difference
from (select t.*
             min(performance) over (partition by session) as min_performance,max(performance) over (partition by session) as max_performance
      from t
     ) t
group by t.session,min_performance,max_performance;
本文链接:https://www.f2er.com/3122091.html

大家都在问