如何找到列值之差最大的那对行按某个列值分组
How to find the pair of rows where the difference of columns value is maximum group by some column value
我有一个table类似于下面的,
我想找到每个会话的性能差异最大的一对中心。所以,我想要一个像下面这样的 table,
我正在努力为 h2 数据库形成正确的查询。
您可以自行加入 table 并使用相关子查询进行过滤:
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
)
或者您可以使用 window 函数:
select *
from (
select
t1.session,
t1.center center1,
t2.center center2,
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;
我有一个table类似于下面的,
我想找到每个会话的性能差异最大的一对中心。所以,我想要一个像下面这样的 table,
我正在努力为 h2 数据库形成正确的查询。
您可以自行加入 table 并使用相关子查询进行过滤:
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
)
或者您可以使用 window 函数:
select *
from (
select
t1.session,
t1.center center1,
t2.center center2,
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;