简体   繁体   English

获取基于状态的最新记录所需的SQL?

[英]SQL needed for getting latest records based on Status?

I have a table TRX which has multiple values TRXID for a given SRCID sample data set shown below. 我有一个表TRX,它对于给定的SRCID样本数据集具有多个值TRXID,如下所示。

TRXID       STATUS  TIMESTAMP                           SRCID
839         EN      30-OCT-14 11.08.13.597000000 AM     B0D35D0168G
1189        MO      30-OCT-14 11.13.19.554000000 AM     B0D35D0168G
1549        CA      30-OCT-14 12.13.42.246000000 PM     B0D35D0168G

1666        EN      30-OCT-14 02.43.22.271000000 PM     A0D77E2168G
2221        CA      30-OCT-14 05.49.16.712000000 PM     A0D77E2168G
2244        EN      31-OCT-14 11.21.18.146000000 AM     A0D77E2168G  ...

I want to get all SRCID which have latest status = 'CA' based on latest TIMESTAMP only. 我想基于最新的TIMESTAMP获得所有具有最新状态='CA'的SRCID。 so eg if we ran the query for above data set we would only get 'B0D35D0168G' as a result. 所以,例如,如果我们运行上述数据集的查询,我们只会得到'B0D35D0168G'。

This will work in Oracle: 这将在Oracle中有效:

SELECT srcid FROM (
    SELECT srcid, status, ROW_NUMBER() OVER ( PARTITION BY srcid ORDER BY timestamp DESC ) AS rn
      FROM trx
) WHERE status = 'CA' AND rn = 1;

It will work if you need to retrieve additional columns as well (eg, if you need to know what the last value of timestamp is). 如果您还需要检索其他列,它将起作用(例如,如果您需要知道timestamp的最后一个值是什么)。

SELECT trxid, srcid, timestamp FROM (
    SELECT trxid, srcid, timestamp, status, ROW_NUMBER() OVER ( PARTITION BY srcid ORDER BY timestamp DESC ) AS rn
      FROM trx
) WHERE status = 'CA' AND rn = 1;

Here is the "most recent" pattern I've used quite successfully for several years now. 这是我几年来成功使用的“最新”模式。 If the key and date field form an index, it is really fast. 如果键和日期字段形成索引,则它非常快。

select  *
from    trx t1
where   t1.status = 'CA'
   and  t1.timestamp =(
      select  Max( timestamp )
      from    trx
      where   status = t1.status
         and  timestamp <= SysDate );

The last line of the subquery may be omitted if future dates are not possible. 如果未来日期不可能,则可省略子查询的最后一行。 Either way, the query should perform only index seeks. 无论哪种方式,查询应该只执行索引搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM