sqlsql-server

Select 1 row from the dataset which satisfies a particular condition


I require some help.

Database Design:

Device Table

Id Firmware
1 1.1
2 1.2
3 1.1
4 1.1
5 1.2

Commissioned Device Table

DeviceId PersonId
1 2
2 4
3 1

GPS Location Table

DeviceId Longitude Lattitude RecordedDate
1 2 3 2025-08-01
2 4 1 2025-08-01
3 1 3 2025-08-01
1 2 4 2025-08-01
2 4 2 2025-08-01
3 1 6 2025-08-01
1 2 6 2025-08-01
2 4 8 2025-08-01
3 1 9 2025-08-01

End result that I want is the following:

DeviceId Longitude Lattitude RecordedDate
1 2 3 2025-08-01
2 4 1 2025-08-01
3 1 3 2025-08-01

So the idea is that there can be multiple entries of the Device in the table, but I need to select only the one which have highest RecordedDate. And devices should only be those available in the CommissionedDevice table.

What I have tried?

I have tried various approaches, like distinct, cte, group by, but so far I am unable to achieve the desired results.

Please let me know what approach should be taken, I read there is something like rank which can also help.

Thanks.


Solution

  • You can use Row_Number to number the rows for each device ID. Then use a common table expression (CTE) to show just the rows with rn=1.

    WITH CTE as
    (
    SELECT G.DeviceID, 
           G.Longitude,     
           G.Lattitude,     
           G.RecordedDate, 
           Row_Number() OVER (PARTITION BY G.DeviceID ORDER BY RecordedDate desc) as rn
    FROM GPSLocation G
    INNER JOIN   CommissionedDevice CD ON CD.DeviceID=G.DeviceID
    )
    SELECT * 
    FROM CTE 
    WHERE rn=1
    

    fiddle

    fiddle with time added

    DeviceID Longitude Lattitude RecordedDate rn
    1 2 3 2025-08-01 1
    2 4 8 2025-08-01 1
    3 1 3 2025-08-01 1