SQL-如何为给定范围内的每个日期选择最新的可用记录

时间:2019-02-25 12:21:53

标签: sql oracle

我在数据库中有一个表(DATA_RECORDS),其中包含同一日期但在不同时间(从2015年到2018年)的多个记录。我想做的是选择给定日期范围内的所有记录,然后选择每个日期可用的最新记录。我在SQL中拥有的当前代码是:

SELECT NAME, DATE_LOADED, R_ID 
    FROM DATA_RECORDS 
    WHERE ((DATE_LOADED>=to_date('01/12/2018 00:00:00', 'dd/mm/yyyy HH24:MI:SS'))
    AND (DATE_LOADED<=to_date('31/12/2018 23:59:59', 'dd/mm/yyyy HH24:MI:SS')))
    ORDER BY DATE_LOADED DESC;

列名称为“ NAME”,“ DATE_LOADED”和“ R_ID”。 上面给出了以下结果:

NAME      |DATE_LOADED         |R_ID
-------------------------------------
RECORD_1  |31/12/2018 17:36:38 |1234
RECORD_2  |31/12/2018 10:15:11 |1235
RECORD_3  |30/12/2018 16:45:23 |1236
RECORD_4  |30/12/2018 09:06:54 |1237
RECORD_5  |30/12/2018 07:53:30 |1238

等...如您所见,每天的上传次数也不一致。

我要选择的是

NAME      |DATE_LOADED         |R_ID
-------------------------------------
RECORD_1  |31/12/2018 17:36:38 |1234
RECORD_3  |30/12/2018 16:45:23 |1236

我对SQL还是很陌生,因此可以提供任何帮助。

N.B:我正在使用Oracle SQL Developer,并且只能对数据库进行只读访问,因此无法创建任何新表或修改当前表。

2 个答案:

答案 0 :(得分:1)

我将此逻辑写为:

SELECT NAME, DATE_LOADED, R_ID 
FROM DATA_RECORDS 
WHERE DATE_LOADED >= DATE '2018-01-12' AND
      DATE_LODED < DATE '2018-12-31'
ORDER BY DATE_LOADED DESC;

然后一个简单的方法是ROW_NUMBER() -仅从日期/时间值中提取日期:

SELECT NAME, DATE_LOADED, R_ID
FROM (SELECT NAME, DATE_LOADED, R_ID ,
             ROW_NUMBER() OVER (PARTITION BY TRUNC(DATE_LOADED) ORDER BY DATE_LOADED DESC) as seqnum
      FROM DATA_RECORDS 
      WHERE DATE_LOADED >= DATE '2018-01-12' AND
            DATE_LODED < DATE '2018-12-31'
     ) dr
WHERE seqnum = 1
ORDER BY DATE_LOADED DESC;

答案 1 :(得分:0)

您可以使用相关子查询

select * from tablename a where date in
   (select max(DATE_LOADED) from tablename b where cast(a.DATE_LOADED as date)=cast(b.DATE_LOADED as date)) and 
   ((DATE_LOADED>=to_date('01/12/2018 00:00:00', 'dd/mm/yyyy HH24:MI:SS'))
    AND (DATE_LOADED<=to_date('31/12/2018 23:59:59', 'dd/mm/yyyy HH24:MI:SS')))