You can use the ranking function ROW_NUMBER() OVER(PARTITION BY ... ORDER BY ...
like this:
WITH CTE
AS
(
Select TOP 1000
FH.AtmKey,
F.FAULTDESC,
FH.FAULTSTARTTIME,
FH.FAULTENDTIME,
FM.FaultIDMSTR,
ROW_NUMBER() OVER(PARTITION BY FM.FaultIDMSTR
ORDER BY FH.FAULTSTARTTIME DESC) AS RN
From FAULTS_HISTORY FH
INNER JOIN FAULTDEFS F ON FH.FaultID = F.FAULTID
INNER JOIN FAULTMAP FM ON F.FAULTID = FM.FaultID
where FH.AtmKey in ('11487676154140993')
)
SELECT
AtmKey,
AULTDESC,
FAULTSTARTTIME,
FAULTENDTIME,
FaultIDMSTR
FROM CTE
WHERE RN = 1;
This will give you the rows with maximum of FH.FAULTSTARTTIME
for each FM.FaultIDMSTR
, if you want to group by another column put it in the PARTITION BY
column.
Note that: Try to avoid the old JOIN
syntax, and use the ANSI-92 syntax, see this: