获取最大日期的记录
假设我提取了一组数据。
即
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)
但是我的查询真的很长...是否有更紧凑的方法使用分析函数来执行相同的操作?
Let's assume I extract some set of data.
i.e.
SELECT A, date
FROM table
I want just the record with the max date (for each value of A). I could write
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)
But my query is really long... is there a more compact way using ANALYTIC FUNCTION to do the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
分析函数方法看起来类似于
注意,根据您想要如何处理联系(或者数据模型中是否可能存在联系),您可能需要使用
ROW_NUMBER
或DENSE_RANK
分析函数而不是RANK
。The analytic function approach would look something like
Note that depending on how you want to handle ties (or whether ties are possible in your data model), you may want to use either the
ROW_NUMBER
or theDENSE_RANK
analytic function rather thanRANK
.如果
date
和col_date
是相同的列,您应该简单地执行以下操作:为什么不使用:
否则:
If
date
andcol_date
are the same columns you should simply do:Why not use:
Otherwise:
您还可以使用:
You could also use:
A 是键,max(date) 是值,我们可以将查询简化如下:
A is the key, max(date) is the value, we might simplify the query as below:
贾斯汀·凯夫(Justin Cave)的答案是最好的,但如果您想要其他选择,请尝试以下操作:
Justin Cave answer is the best, but if you want antoher option, try this:
从 Oracle 12C 开始,您可以使用
FETCH FIRST ROW ONLY
获取特定数量的行。在您的情况下,这意味着
ORDER BY
,因此应考虑性能。NULLS LAST
是为了防止您的字段中可能存在空值。Since Oracle 12C, you can fetch a specific number of rows with
FETCH FIRST ROW ONLY
.In your case this implies an
ORDER BY
, so the performance should be considered.The
NULLS LAST
is just in case you may have null values in your field.