Oracle SQL:查找每个ID号的最新事务

时间:2014-12-18 20:26:39

标签: sql oracle

我在Oracle SQL Developer中编写查询。 基本上我想找到每个ID最近的date_transaction记录。现在我的查询最多返回两个记录,每个ID,每个状态一个。

我当前的查询:

select id, to_char(MAX(DATE_TRANSACTION),'MM/DD/YY HH24:MM:SS'), status, dkld.note
from db_name.table1_name mtlr
inner join (select * from db_name.table2_name where table_number = 308) dkld
on dkld.integer_key = mtlr.status
where id <> 0 and mtlr.date_transaction between (systimestamp - interval '1' hour) and systimestamp
group id, status, dkld.note
order by id

示例查询返回:

|  ID  |  max(date_transaction)  |  Status  |    Note    |
|--------------------------------------------------------|
|  2   |    12/18/14 13:12:24    |     3    | In Transit |
|  2   |    12/18/14 13:12:22    |     4    | Arrived    |
|  3   |    12/18/14 13:12:49    |     4    | Arrived    |
|  4   |    12/18/14 13:12:05    |     3    | In Transit |
|  4   |    12/18/14 13:12:23    |     4    | Arrived    |

我对SQL很陌生,不知道从哪里开始。如何缩小范围以仅获取每个ID的最新记录?

2 个答案:

答案 0 :(得分:1)

SELECT *
from db_name.table1_name mtlr
WHERE NOT EXISTS (
  SELECT * from db_name.table1_name nx
  WHERE nx.id = mtlr.id
  AND nx.DATE_TRANSACTION > mtlr.DATE_TRANSACTION
  );

答案 1 :(得分:0)

Max在技术上将数据分组。由于您有4列,并且所有4列的组合都是唯一的,因此它将有两个条目。 我没有测试它,如果你在下面做,它应该只返回每个ID(或概念)的一个条目

select id, to_char(MAX(DATE_TRANSACTION),'MM/DD/YY HH24:MM:SS')
from db_name.table1_name mtlr
inner join (select * from db_name.table2_name where table_number = 308) dkld
on dkld.integer_key = mtlr.status
where id <> 0 and mtlr.date_transaction between (systimestamp - interval '1' hour) and systimestamp
group by id
order by id desc