SELECT DISTINCT on one column, return multiple other columns (SQL Server)
You are having a right join, so if you have more than 1 record for device serial number in table GPSReport
, it will get all those record and joint then to the unique list received from SELECT DISTINCT device_serial FROM GPSReport
.
WITH DEDUPE AS (
SELECT *
, ROW_NUMBER() OVER ( PARTITION BY what_you_want_for_distinct ORDER BY what_you_want_for_distinct) AS OCCURENCE
FROM tablename
)
SELECT * FROM DEDUPE
WHERE
OCCURENCE = 1
SELECT * FROM
GPSReport AS G1
JOIN (SELECT device_serial, max(datetime) as mostrecent
FROM GPSReport group by device_serial) AS G2
ON G2.device_serial = G1.device_serial and g2.mostrecent = g1.datetime
ORDER BY G1.device_serial