【问题标题】:Oracle SQL: how to show only one max per groupOracle SQL:如何每组只显示一个最大值
【发布时间】:2020-12-26 15:27:07
【问题描述】:

大家好,首先感谢您的宝贵时间。 我有这个数据

数据:

如果有一个组有两个相同的最大值,我必须获得每个组的最大值

A 40 23/56/1982
A 40 31/4/5521

只显示其中一个。 像这样

到目前为止,我已经尝试了两种方法,它们只有在每组没有任何重复的最大值时才有效。

Oracle SQL 代码:

SELECT DISTINCT SUB.GRUPO,SUBG.FECHA,SUBG.VALOR
FROM T2 SUBG
LEFT JOIN T2 SUB2
ON SUBG.GRUPO = SUB2.GRUPO AND SUBG.VALOR < SUB2.VALOR
WHERE SUB2.VALOR is NULL
ORDER BY GRUP
SELECT GRUPO, FECHA
FROM T2
WHERE VALOR IN (SELECT MAX(VALOR) FROM T2 GROUP BY GRUPO)
ORDER BY GRUPO

有什么办法吗?

【问题讨论】:

    标签: sql oracle datetime max greatest-n-per-group


    【解决方案1】:

    使用row_number()

     select * from (select a.*, row_number() over(partition by GRUPO order by VALOR desc) rn
     from T2 a
    ) a where rn=1
    

    【讨论】:

      【解决方案2】:

      如果您想要每个组的最大日期,聚合就足够了:

      select 
          groupo, 
          max(fecha) fecha
      from t2
      group by groupo
      

      如果您还想要相应的valor,那么由于结果集中只有 3 列,这可能是使用keep 的好地方:

      select 
          groupo, 
          max(fecha) fecha, 
          max(valor) keep(dense_rank last order by fecha) valor
      from t2
      group by groupo
      

      【讨论】:

        【解决方案3】:

        更传统的方法是使用相关子查询:

        select distinct groupo, fecha, valor
        from t2 t
        where valor = (select max(valor)
                       from t2
                       where groupo = t.groupo);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-04
          • 2012-11-07
          • 2017-04-17
          • 2018-03-06
          • 2015-07-03
          • 1970-01-01
          • 2022-10-05
          相关资源
          最近更新 更多