繁体   English   中英

根据快照日期返回最新记录

[英]Return the most recent record according to a snapshot date

我有一个包含4列的表(snapshotDate,systemID,companyID,State),该表可以为每个系统在相同状态下具有相同companyID的不同快照。

我想编写一个查询,以返回每个系统中具有相同companyID和相同状态的当月每个记录的最新记录。

例如:

snapshotDate    systemID    companyID   State
12/31/2017           A        2         FL
12/30/2017           A        2         FL
12/29/2017           A        2         FL
03/25/2018           B        5         WA
03/20/2018           B        5         WA

在这种情况下,我希望结果如下:

snapshotDate    systemID    companyID   State
12/31/2017           A        2         FL 
03/25/2018           B        5         WA

谢谢迈克

您可以使用此查询

select max(snapshotDate) snapshotDate ,systemID, companyID, State 
from tablename 
group by systemID, companyID, State;

window functiontop(1)一起使用

select top(1) with ties systemID, *
from table t
order by row_number() over (partition by systemID order by snapshotDate desc)

您也可以改用subquery

select * from table t
where snapshotDate = (select max(snapshotDate) from table where systemID = t.systemID)

但是,根据您的示例数据,您可以通过group by子句进行操作

select max(snapshotDate) snapshotDate, systemID, companyID, State
from table t
group by systemID, companyID, State

您可以使用WINDOW FUNCTION Row_Number()实现此WINDOW FUNCTION Row_Number()

尝试这个:

SELECT snapshotDate,systemID,companyID,State 
FROM(
    SELECT snapshotDate,systemID,companyID,State
        ,ROW_NUMBER() OVER(PARTITION BY systemID ORDER BY snapshotDate DESC)RN  
    FROM Your_Table
    )D
WHERE D.RN = 1

暂无
暂无

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

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