为表分配了DeviceName,IPaddress和CreateTime。
我需要查找具有重复IP的设备,但仅显示具有最新创建时间的设备。这是在MSSQL中
我获得了具有重复IP的设备,但是我不知道如何只显示最后创建的设备。使用Max(CreateTime)获取结果时遇到问题
到目前为止,我有这个查询来查找具有重复IP的设备
select devicename,IPAddress from devices where ipaddress IN
(SELECT IPAddress FROM Devices GROUP BY IPAddress HAVING COUNT(*) > 1)
答案 0 :(得分:1)
我会这样:
select d.*
from devices d
where d.createtime = (select max(d2.createtime)
from devices d2
where d2.ip = d.ip
);
如果您还想消除重复项,可以执行以下操作:
select d.*
from devices d
where d.createtime = (select max(d2.createtime)
from devices d2
where d2.ip = d.ip
) and
exists (select 1
from devices d2
where d2.ip <> d.ip
);
答案 1 :(得分:1)
我可能会考虑使用Rank
功能,如下所示。它将按createdate对所有重复的IP进行排名,然后选择仅排名第一的所有IP地址。
select
devicename,
IPAddress
From
(
select
devicename,
IPAddress
Rank() OVER (PARTITION BY IPAddress ORDER BY CreateDate DESC) AS Rnk
from devices
) Query
Where rnk = 1