我正在尝试编写一个查询,从每个唯一设备的GPSReport表格返回最近的GPS位置.表中有50个设备,所以我只需要返回50行.
这是我到目前为止(不工作)
SELECT TOP(SELECT COUNT(DISTINCT device_serial) FROM GPSReport) * FROM GPSReport AS G1 RIGHT JOIN (SELECT DISTINCT device_serial FROM GPSReport) AS G2 ON G2.device_serial = G1.device_serial ORDER BY G2.device_serial,G1.datetime DESC
这返回50行,但是不返回每个device_serial的唯一行.它返回第一个设备的所有报告,然后返回第二个设备的所有报告等.
在一个查询中我正在尝试做什么?
解决方法
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