如何从 table 中找到最大值和最小值以及另一列值?

How to find the maximum and minimum value along with another column value from a table?

我有一个 table 这样的:

我想找到最大和最小效率及其对应的中心名称,按会话分组 - 像这样:

我试过了

Select max(Efficiency) as max_Efficiency, Center as max_Center, 
       min(Efficiency) as min_Efficiency, Center as min_Center 
from myTable
group by session

但它不起作用,出现错误。如果我离开中心(两种情况),它会起作用,但我也需要中心名称。

您可以尝试这样的操作:

select session, max_efficiency, max_center, min_Efficiency, min_center from (
    select tbl.*, 
        case when tbl.session = nt.session and tbl.max_efficiency = Efficiency then nt.center end max_center,
        case when tbl.session = nt.session and tbl.max_efficiency = Efficiency then nt.center end min_center
    from (
        select  session,
                max(Efficiency) max_Efficiency,
                min(Efficiency) min_Efficiency
        from myTable
        group by session
    ) tbl
    join myTable mt
    on mt.session = tbl.session
) where (max_center is not null and min_center is not null)

如果您的 table 有很多数据,我不确定执行时间,但这应该可以解决问题。

可能有更简单的方法来trim这个查询。

SQL 查询可以如下所示:

select t1.Session,
       t1.max_Efficiency,
       t2.Center as max_Center,
       t1.min_Efficiency,
       t3.Center as min_Center
from (
  select Session, 
         max(Efficiency) as max_Efficiency, 
         min(Efficiency) as min_Efficiency
  from myTable
  group by Session
) as t1
inner join myTable t2 on t2.session = t1.session and t2.efficiency = t1.max_Efficiency
inner join myTable t3 on t3.session = t1.session and t3.efficiency = t1.min_Efficiency;

结果是

用window函数ROW_NUMBER():

select 
  t.session,
  max(case when t.maxrn = 1 then efficiency end) max_Efficiency,
  max(case when t.maxrn = 1 then center end) max_Center,
  max(case when t.minrn = 1 then efficiency end) min_Efficiency,
  max(case when t.minrn = 1 then center end) min_Center
from (
  select *,
    row_number() over (partition by session order by efficiency desc) maxrn,
    row_number() over (partition by session order by efficiency asc) minrn
  from tablename
) t
where t.maxrn = 1 or t.minrn = 1  
group by t.session

查看 demo(使用 SQL 服务器)。

> session | max_Efficiency | max_Center | min_Efficiency | min_Center
> ------: | -------------: | :--------- | -------------: | :---------
>       1 |             96 | A          |             66 | B         
>       2 |             98 | C          |             32 | D