获取最近一次的最新单行

时间:2014-05-19 06:50:48

标签: oracle plsql

我正在使用Oracle 10g。我有一个表TABLE_X,其中包含以下数据:

             **Sup_ID     Start_Date     End_Date**
               S001       01-01-2010     31-12-2020
               S001       01-01-2011     31-12-2019
               S001       01-01-2012     31-12-2018
               S002       01-01-2010     31-12-2014
               S002       01-01-2014     31-12-2015
               S003       01-01-2012     30-09-2013
               S004       01-01-2010     31-12-2014
               S004       01-01-2011     31-12-2013

现在我需要编写一个SQL查询来获取每个Sup_ID最新的开始和结束日期,结果如下:

            **Sup_ID     Start_Date        End_Date**
              S001       01-01-2012        31-12-2018
              S002       01-01-2014        31-12-2015
              S003       01-01-2012        30-09-2013
              S004       01-01-2011        31-12-2013

请注意,我使用的是Oracle DBMS。谁可以在这方面帮助我? 谢谢大家。

3 个答案:

答案 0 :(得分:3)

一个简单的max()聚合函数应该可以解决问题

select *
from Table1
where ("Sup_ID", "Start_Date") in (select "Sup_ID", max("Start_Date") 
                       from Table1
                       group by "Sup_ID");

Fiddle

答案 1 :(得分:1)

试试这个:

SELECT T2.Sup_ID,T1.Start_Date,T2.End_Date
FROM TableName T1 JOIN
(SELECT Sup_ID,MAX(End_Date) as End_Date
 FROM TableName
 GROUP BY Sup_ID) T2 ON T1.Sup_ID=T2.Sup_ID AND T1.End_Date=T2.End_Date
ORDER BY T2.Sup_ID

答案 2 :(得分:1)

Select * from 
(
select *,rn=row_number()over(partition by Sup_ID order by Start_Date desc) from table
)x
where x.rn=1