【问题标题】:How to find the maximum and minimum value along with another column value from a table?如何从表中找到最大值和最小值以及另一列值?
【发布时间】:2020-03-08 06:26:04
【问题描述】:

我有一张这样的桌子:

我想通过相应的中心名称按会话分组找到最大和最小效率 - 像这样:

我试过了

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

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

【问题讨论】:

  • 如果将行 (1, E, 96) 添加到表中,预期的结果是什么?
  • A 或 E,任何一个,谢谢。
  • 我不知道 h2,但你可以有一个子查询,它返回每个会话及其最大和最小效率值。然后将该结果与原始表连接起来。
  • 我考虑过,还没有尝试,如果有更好的选择,谢谢@jarlh。

标签: java sql h2


【解决方案1】:

带窗口函数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 Server)。

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

【讨论】:

【解决方案2】:

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;

结果是

【讨论】:

  • 谢谢,它可以工作,但是当有相同的多个最大/最小答案时 - 它会显示所有。我可以阻止它们,只显示一个。再次感谢。
  • 你能举一个例子来说明期望的结果,除了一个之外,所有的最小/最大行都被阻止了吗?
【解决方案3】:

你可以试试这样的:

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)

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

也许有一种更简单的方法可以减少这个查询。

【讨论】:

  • 它有效,非常感谢。 mytable 本身是一个很大的查询,所以执行时间比预期的要高。
猜你喜欢
  • 2020-12-02
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
相关资源
最近更新 更多