2015-03-19 52 views
4

我有多個表並連接每個表。結果是這樣的:SQL排序和選擇一個最接近的值

 CarId CarLat CarLon Path Minute Distance 
     325 36.000 37.200 H4  74  250 
     344 36.050 37.040 H6  75  500 
     365 36.300 37.600 H4  76  750 
     311 36.060 37.080 H5  77  800 

正如你所看到的,路徑有2個H4,我想要顯示更小的分鐘路徑。像這樣:

 CarId CarLat CarLon Path Minute Distance 
     325 36.000 37.200 H4  74  250 
     344 36.050 37.040 H6  75  500 
     311 36.060 37.080 H5  77  800 

我該怎麼做?

回答

5

您可以使用SQL SERVER ROW_NUMBER來確定這一點。

因此,像

;WITH Vals AS (
     SELECT *, 
       ROW_NUMBER() (PARTITION BY Path ORDER BY Minute) RowID 
     FROM Table 
) 
SELECT * 
FROM Vals 
WHERE RowID = 1 
2

MIN分鐘和GROUP BY

SELECT CarId, CarLat, CarLon, Path, MIN(Minute), Distance 
FROM table 
GROUP BY CarId, CarLat, CarLon, Path, Distance