7

我有以下 SQL:

select code, distance from places;    

输出如下:

CODE    DISTANCE            LOCATION
106     386.895834130068    New York, NY
80      2116.6747774121     Washington, DC
80      2117.61925131453    Alexandria, VA
106     2563.46708627407    Charlotte, NC

我希望能够只获得一个代码和最近的距离。所以我希望它返回这个:

CODE    DISTANCE            LOCATION
106     386.895834130068    New York, NY
80      2116.6747774121     Washington, DC

我最初有这样的事情:

SELECT code, min(distance), location
GROUP BY code
HAVING distance > 0 
ORDER BY distance ASC

如果我不想获得与最短距离相关的正确位置,则最小值可以正常工作。我如何获得最小(距离)和正确的位置(取决于表中插入的顺序,有时您最终可能会得到纽约距离,但位置中的夏洛特)。

4

3 回答 3

8

要获得正确的关联位置,您需要加入一个子选择,该子选择在外部主表中的距离与子选择中派生的最小距离匹配的条件下获得每个代码的最小距离。

SELECT a.code, a.distance
FROM   places a
INNER JOIN
(
    SELECT   code, MIN(distance) AS mindistance
    FROM     places
    GROUP BY code
) b ON a.code = b.code AND a.distance = b.mindistance
ORDER BY a.distance
于 2012-07-27T08:30:08.713 回答
0

您可以尝试在最小分组和原始表之间进行嵌套查找。

这似乎可以解决问题

SELECT MinPlaces.Code, MinPlaces.Distance, Places.Location 
FROM Places INNER JOIN
(
    SELECT Code, MIN(Distance) AS Distance
    FROM Places
    GROUP BY Code
    HAVING MIN(Distance) > 0 
) AS MinPlaces ON Places.Code = MinPlaces.Code AND Places.Distance = MinPlaces.Distance
ORDER BY MinPlaces.Distance ASC

更新:使用以下测试:

DECLARE @Places TABLE ( Code INT, Distance FLOAT, Location VARCHAR(50) )

INSERT INTO @Places (Code, Distance, Location)
VALUES
(106, 386.895834130068, 'New York, NY'),
(80, 2116.6747774121, 'Washington, DC'),
(80, 2117.61925131453, 'Alexandria, VA'),
(106, 2563.46708627407, 'Charlotte, NC')

SELECT MinPlaces.Code, MinPlaces.Distance, P.Location 
FROM @Places P INNER JOIN
(
    SELECT Code, MIN(Distance) AS Distance
    FROM @Places
    GROUP BY Code
    HAVING MIN(Distance) > 0 
) AS MinPlaces ON P.Code = MinPlaces.Code AND P.Distance = MinPlaces.Distance
ORDER BY MinPlaces.Distance ASC

这会产生:

在此处输入图像描述

于 2012-07-27T08:01:51.747 回答
0

你没有说你的 DBMS。以下解决方案适用于 SQL Server。

WITH D AS (
   SELECT code, distance, location,
      Row_Number() OVER (PARTITION BY code ORDER BY distance) Seq
   FROM places
)
SELECT *
FROM D
WHERE Seq = 1

如果您有一个带有唯一代码的表,并且在 [代码,距离] 上的 Places 表中有一个索引,那么 CROSS APPLY 解决方案可能会更好:

SELECT
   X.*
FROM
   Codes C
   CROSS APPLY (
      SELECT TOP 1 *
      FROM Places P
      WHERE C.Code = P.Code
      ORDER BY P.Distance
   ) X

直到很久以后,我才能为 mysql 解决方案。

PS您不能依赖广告订单。不要尝试!

于 2012-07-27T08:03:54.823 回答