我有以下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
如果我不想获得与最小距离相关联的正确位置,则min工作正常。我如何获得最小(距离)和正确的位置(取决于表中插入的顺序,有时你可能最终得到纽约距离,但夏洛特在位置)。
答案 0 :(得分:6)
要获得正确的关联位置,您需要加入一个子选择,该子选择在外部主表中的距离与子选择中派生的最小距离匹配的条件下获得每个代码的最小距离。
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
答案 1 :(得分: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
这会产生:
答案 2 :(得分: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
如果您有一个包含唯一代码的表格,以及[代码,距离]上的“地方”表格中的索引,那么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的解决方案。
P.S。您不能依赖于广告订单。别试试!