I have a table in sql server. It has a pid field used as the primary key, and a field called deviceid that has the name of the device. Example:
pid deviceid field3 field4
1 Device1 test test
2 Device2 test2 test2
3 Device1 test3 test3
4 Device2 test4 test4
For the query, I need to select * from the table where pid is the maximum for each device. Example result:
pid deviceid field3 field4
3 Device1 test3 test3
4 Device2 test4 test4
I am not sure how to do this. Does anyone have any ideas?
The closest I got:
Select MAX(pid) from TheTable Group By deviceid;
This works, but it gives me the maximum number of pid for each device in the results, and I need the entire field for this entry. Adding select fields to other fields led to errors saying that the fields should be listed in the group by clause ... Does anyone know how to do this?
source