SQL查询以从数据库获取最新坐标

时间:2018-11-05 05:03:43

标签: sql sql-server

作为新手,我有一个问题:我有一个FleetTracker的小项目,我想在一天中获取每个舰队的最新坐标,所以我有如下的gps数据库:

gpsDateTime         | long | lat  | fleetNumber
--------------------+------+------+-------------
2018-10-03 14:11:00 | 123  | -123 | ABC1234
2018-10-03 14:21:00 | 124  | -124 | ABC1234
2018-10-03 14:31:00 | 125  | -125 | ABC1234
2018-10-03 14:41:00 | 126  | -126 | ABC1234
2018-10-03 14:51:00 | 127  | -127 | ABC1234
......
2018-10-04 14:11:00 | 123  | -123 | ABC1234
2018-10-04 14:21:00 | 124  | -124 | ABC1234
2018-10-04 14:31:00 | 125  | -125 | ABC1234
2018-10-04 14:41:00 | 126  | -126 | ABC1234
2018-10-04 14:51:00 | 127  | -127 | ABC1234
......    
2018-10-03 14:11:00 | 123  | -123 | JKL4321
......
2018-10-03 14:21:00 | 124  | -124 | JKL4322
2018-10-03 14:31:00 | 125  | -125 | JKL4323
2018-10-03 14:41:00 | 126  | -126 | JKL4324
2018-10-03 14:51:00 | 127  | -127 | JKL4325
2018-10-04 14:11:00 | 123  | -123 | JKL4321
2018-10-04 14:21:00 | 124  | -124 | JKL4322
2018-10-04 14:31:00 | 125  | -125 | JKL4323
2018-10-04 14:41:00 | 126  | -126 | JKL4324
2018-10-04 14:51:00 | 127  | -127 | JKL4325

我的查询:

SELECT
    MAX(gpsDateTime) AS Timee,
    long, lat, fleetNumber 
FROM
    GPS 
WHERE
    CAST(gpsDateTime AS DATE) =  '2018-10-03' 
GROUP BY
    fleetNumber, gpsDateTime, long, lat 
ORDER BY
    Timee DESC

但结果返回如下:

2018-10-03 14:11:00 |123 |-123|ABC1234
2018-10-03 14:21:00 |124 |-124|ABC1234
2018-10-03 14:31:00 |125 |-125|ABC1234
2018-10-03 14:41:00 |126 |-126|ABC1234
2018-10-03 14:51:00 |127 |-127|ABC1234

2018-10-03 14:11:00 |123 |-123|JKL4321
2018-10-03 14:21:00 |124 |-124|JKL4322
2018-10-03 14:31:00 |125 |-125|JKL4323
2018-10-03 14:41:00 |126 |-126|JKL4324
2018-10-03 14:51:00 |127 |-127|JKL4325

我需要这样的结果(每个车队号只有最新的一个):

2018-10-03 14:51:00 |127 |-127|ABC1234
2018-10-03 14:51:00 |127 |-127|JKL4325

先谢谢了。

2 个答案:

答案 0 :(得分:2)

您可以使用row_number()

sum of even number = 2550
sum of odd number = 2500
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.print(0x434100, 0x11db7c)
    /tmp/sandbox052575152/main.go:18 +0xc0
main.main()
    /tmp/sandbox052575152/main.go:14 +0x120

答案 1 :(得分:0)

使用Windows函数作为更好的选择也是一种更好的选择,您也可以通过独立于SQL Server的派生表来满足您的要求,

  select B.Timee,A.long,A.lat, A.fleetNumber 
  from GPS A inner join
  (select max(gpsDateTime) as Timee,fleetNumber 
  from GPS 
  Where cast(gpsDateTime as Date) =  '2018-10-03' 
  group by fleetNumber,gpsDateTime) B
  on A.gpsDateTime=B.Timee and A.fleetNumber= B.fleetNumber