让我们假设我提取了一些数据集。
即
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有没有更紧凑的方法可以做到这一点
分析函数方法看起来像
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_NUMBER
或DENSE_RANK
分析函数,而不是RANK
。
如果date
和col_date
是相同的列,则只需执行以下操作:
SELECT A, MAX(date) FROM t GROUP BY A
为什么不使用:
WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME GROUP BY A )
SELECT t.A, t.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
您也可以使用:
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
A是键,max(date)是值,我们可以将查询简化为:
SELECT distinct A, max(date) over (partition by A)
FROM TABLENAME
Justin Cave的答案是最好的,但如果你想选择其他选项,可以试试这个:
select A,col_date
from (select A,col_date
from tablename
order by col_date desc)
where rownum<2
由于Oracle12C,您可以使用FETCH FIRST ROW ONLY
获取特定数量的行。在您的情况下,这意味着ORDER BY
,因此应该考虑性能。
SELECT A, col_date
FROM TABLENAME t_ext
ORDER BY col_date DESC NULLS LAST
FETCH FIRST 1 ROW ONLY;
NULLS LAST
只是为了防止您的字段中有空值。
SELECT mu_file, mudate
FROM flightdata t_ext
WHERE mudate = (SELECT MAX (mudate)
FROM flightdata where mudate < sysdate)