Oracle:获得团队的最大价值?

Mar*_*son 9 sql oracle

给定这样的表格,每个监视器的最新校准信息是什么?换句话说,我想找到每个监视器的最大日期值.特定于Oracle的功能适用于我的应用程序.

monitor_id     calibration_date  value
----------     ----------------  -----
1              2011/10/22        15
1              2012/01/01        16
1              2012/01/20        17
2              2011/10/22        18
2              2012/01/02        19
Run Code Online (Sandbox Code Playgroud)

此示例的结果如下所示:

1  2012/01/20 17
2  2012/01/02 19
Run Code Online (Sandbox Code Playgroud)

Jus*_*ave 19

我倾向于使用分析函数

SELECT monitor_id,
       host_name,
       calibration_date,
       value
  FROM (SELECT b.monitor_id,
               b.host_name,
               a.calibration_date,
               a.value,
               rank() over (partition by b.monitor_id order by a.calibration_date desc) rnk
          FROM table_name a,
               table_name2 b
         WHERE a.some_key = b.some_key)
 WHERE rnk = 1
Run Code Online (Sandbox Code Playgroud)

您也可以使用相关子查询,但效率较低

SELECT monitor_id,
       calibration_date,
       value
  FROM table_name a
 WHERE a.calibration_date = (SELECT MAX(b.calibration_date)
                               FROM table_name b
                              WHERE a.monitor_id = b.monitor_id)
Run Code Online (Sandbox Code Playgroud)


Jef*_*emp 11

我个人的偏好是这样的:

SELECT DISTINCT
       monitor_id
      ,MAX(calibration_date)
       OVER (PARTITION BY monitor_id)
       AS latest_calibration_date
      ,FIRST_VALUE(value)
       OVER (PARTITION BY monitor_id
             ORDER BY calibration_date DESC)
       AS latest_value
FROM mytable;
Run Code Online (Sandbox Code Playgroud)

一种变化也是使用FIRST_VALUE语法latest_calibration_date.无论哪种方式都有效.