我有一个在FacilityID上有重复记录的SQL表。 FacilityKey是独一无二的。我需要在FacilityID上选择具有重复项的行,但我只想为每个显示一条记录,并且我想选择具有最新(最高)FacilityKey的记录。任何人都可以帮我弄清楚如何写我的查询?我已经尝试了所有我能想到的东西,并在互联网上寻找类似无济于事的东西。我能找到的只是识别重复记录的例子。
答案 0 :(得分:5)
这样的事情应该有效:
select FacilityID, max(FacilityKey)
from Facilities
group by FacilityID
having count(FacilityID)>1
然后如果你想得到所有的字段,就像这样:
select *
from facilities
inner join (
select FacilityID, max(FacilityKey) as maxkey
from Facilities
group by FacilityID
having count(FacilityID)>1
) t on t.FacilityID = facilities.FacilityID and t.maxkey=facilities.FacilityKey
答案 1 :(得分:0)
试试这个:
select
FacilityKey , MAX(FacilityID) AS FacilityID
From YourTable
GROUP BY FacilityKey
HAVING COUNT(*)>1