记录最大日期

问题描述 投票:25回答:6

我们假设我提取了一些数据集。

SELECT A, date
FROM table

我只想要具有最大日期的记录(对于A的每个值)。我可以写

SELECT A, col_date
  FROM TABLENAME t_ext
 WHERE col_date = (SELECT MAX (col_date)
                     FROM TABLENAME t_in
                    WHERE t_in.A = t_ext.A)

但是我的查询真的很长...有一种更紧凑的方式使用ANALYTIC FUNCTION做同样的事情吗?

oracle date max analytic-functions
6个回答
51
投票

分析函数方法看起来像

SELECT a, some_date_column
  FROM (SELECT a,
               some_date_column,
               rank() over (partition by a order by some_date_column desc) rnk
          FROM tablename)
 WHERE rnk = 1

请注意,根据您想要处理关系的方式(或者数据模型中是否可以绑定),您可能需要使用ROW_NUMBERDENSE_RANK解析函数而不是RANK


18
投票

如果datecol_date是相同的列,您应该只做:

SELECT A, MAX(date) FROM t GROUP BY A

为什么不使用:

WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME )
SELECT A, date FROM TABLENAME t JOIN x ON x.A = t.A AND x.m = t.col_date

除此以外:

SELECT A, FIRST_VALUE(date) KEEP(dense_rank FIRST ORDER BY col_date DESC)
  FROM TABLENAME
 GROUP BY A

9
投票

你也可以使用:

SELECT t.*
  FROM 
        TABLENAME t
    JOIN
        ( SELECT A, MAX(col_date) AS col_date
          FROM TABLENAME
          GROUP BY A
        ) m
      ON  m.A = t.A
      AND m.col_date = t.col_date

2
投票

A是关键,max(date)是值,我们可以简化查询,如下所示:

SELECT distinct A, max(date) over (partition by A)
  FROM TABLENAME

1
投票

贾斯汀洞穴的答案是最好的,但如果你想要另一种选择,试试这个:

select A,col_date
from (select A,col_date
    from tablename 
      order by col_date desc)
      where rownum<2

-4
投票
SELECT mu_file, mudate
  FROM flightdata t_ext
 WHERE mudate = (SELECT MAX (mudate)
                     FROM flightdata where mudate < sysdate)
© www.soinside.com 2019 - 2024. All rights reserved.