SQL排序和选择一个最近的值

时间:2015-03-19 09:25:13

标签: sql sql-server sql-server-2008

我有多个表并连接每个表。结果如下:

     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

我该怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

MIN分钟和GROUP BY

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