我有一个包含4列的表(snapshotDate,systemID,companyID,State) 对于同一州的同一公司ID,该表可以为每个系统提供不同的快照。
我想写一个查询来返回每个系统中每个记录的最新记录,每个系统具有相同的公司ID和相同的状态。
例如:
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
由于 麦克
答案 0 :(得分:4)
您可以使用此查询
select max(snapshotDate) snapshotDate ,systemID, companyID, State
from tablename
group by systemID, companyID, State;
答案 1 :(得分:2)
将window function
与 top(1)with ties
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
答案 2 :(得分:0)
您可以使用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