Oracle Query根据约束获取记录

时间:2014-10-10 11:22:26

标签: sql oracle

我有一个以下格式的表格:

ID    FieldA   LastUpdatedDate

1      1       7th Oct, 2014
2      2       7th Oct, 2014
3      3       7th Oct, 2014
4      1       8th Oct, 2014
5      2       8th Oct, 2014
6      1       8th Oct, 2014
7      2       9th Oct, 2014
8      4       9th Oct, 2014

我希望结果如下所示:

ID    FieldA   LastUpdatedDate
4      1        8th Oct, 2014
6      1        8th Oct, 2014
2      2        9th Oct, 2014
3      3        7th Oct, 2014
8      4        9th Oct, 2014

请注意,对于给定日期,FieldA中只能有两个具有相同值的条目,我希望如此 检索基于lastupdateddate的条目,如示例所示。

你能否建议一个给我这样结​​果的查询?

2 个答案:

答案 0 :(得分:0)

如果我理解正确,对于fieldA的每个不同值,您只想显示上一个LastUpdatedDate的记录。 rank分析函数应该可以解决问题:

SELECT ID, FieldA, LastUpdatedDate
FROM   (SELECT ID, FieldA, LastUpdatedDate,
               RANK() OVER (PARTITION BY ID, FieldA 
                            ORDER BY LastUpdatedDate DESC) AS rk
        FROM   my_table)
WHERE  rk = 1

答案 1 :(得分:0)

with lastD as  -- get the last update date for every FieldA
(
select FieldA, max(LastUpdateDate) as lastDate
from my_table
group by FieldA
)
SELECT m.*
FROM   my_table m
JOIN   lastD
  ON   m.FieldA=lastD.FieldA
 AND   m.LastUpdateDate= lastD.lastDate