admin

在一列上选择DISTINCT,返回其他多列(SQL Server)

sql

我正在尝试编写一个查询,该查询从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返回唯一的行。它返回第一个设备的所有报告,然后返回第二个设备的所有报告,依此类推。

我要在一个查询中执行的操作是否可行?


阅读 175

收藏
2021-05-10

共1个答案

admin

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
2021-05-10