SQL - 一系列点之间的最大距离
SQL - Max distance between series of points
抱歉,如果我在其他地方错过了,有没有办法找到点列表 (x,y) 之间的最大距离?
Sample data
你可以交叉连接得到点的所有组合,然后使用勾股定理求出距离。不过,这对于大型数据集来说可能效率低下。
Select *, sqrt(power(a.x-b.x, 2) + power(a.y-b.y, 2)) as Distance
from MyData a
Join MyData b
on a.locationcode > b.locationcode --so you don't get all combination of points a,b and b,a returned
您也可以将其写为 MyData a cross join MyData b
,然后过滤掉连接到自身的行(或忽略它们,因为在这些情况下距离将为 0)。
要得到最大的,像这样:
Select top 1 *, sqrt(power(a.x-b.x, 2) + power(a.y-b.y, 2)) as Distance
from MyData a
Join MyData b
on a.locationcode > b.locationcode
order by Distance desc
(请注意,如果您希望在存在平局的情况下查看所有点集,则可能需要更复杂的东西)。
APH 的回答完全有效,但如前所述,可能 运行 涉及大型数据集的问题。为了未来读者的利益,我将 post 一个对大型数据集应该有效的替代方案:
- 找到点集的质心
- 找到离质心最远的顶点
- 找到最远顶点和任何其他顶点之间的最长边
这是 SQL 服务器的解决方案:
-- Find the centroid of the set of points
DECLARE @centroid_x DECIMAL(18,6);
DECLARE @centroid_y DECIMAL(18,6);
SET @centroid_x = (SELECT AVG(x) FROM points);
SET @centroid_y = (SELECT AVG(y) FROM points);
-- Find the furthest vertex from the centroid
DROP TABLE IF EXISTS #furthest_point;
SELECT
x, y
INTO #furthest_point
FROM (
SELECT
points.x,
points.y,
ROW_NUMBER() OVER (ORDER BY SQRT((points.x - @centroid_x)^2 + (points.y - @centroid_y)^2) DESC) AS rn
FROM points
) fp
WHERE fp.rn = 1;
-- Find the longest edge between the furthest vertex and any other vertex
SELECT
MAX(
SQRT(
POWER(fp.x - p.x, 2) + POWER(fp.y - p.y, 2)
)
) AS maximum_distance
FROM points p
CROSS JOIN furthest_point fp;
抱歉,如果我在其他地方错过了,有没有办法找到点列表 (x,y) 之间的最大距离?
Sample data
你可以交叉连接得到点的所有组合,然后使用勾股定理求出距离。不过,这对于大型数据集来说可能效率低下。
Select *, sqrt(power(a.x-b.x, 2) + power(a.y-b.y, 2)) as Distance
from MyData a
Join MyData b
on a.locationcode > b.locationcode --so you don't get all combination of points a,b and b,a returned
您也可以将其写为 MyData a cross join MyData b
,然后过滤掉连接到自身的行(或忽略它们,因为在这些情况下距离将为 0)。
要得到最大的,像这样:
Select top 1 *, sqrt(power(a.x-b.x, 2) + power(a.y-b.y, 2)) as Distance
from MyData a
Join MyData b
on a.locationcode > b.locationcode
order by Distance desc
(请注意,如果您希望在存在平局的情况下查看所有点集,则可能需要更复杂的东西)。
APH 的回答完全有效,但如前所述,可能 运行 涉及大型数据集的问题。为了未来读者的利益,我将 post 一个对大型数据集应该有效的替代方案:
- 找到点集的质心
- 找到离质心最远的顶点
- 找到最远顶点和任何其他顶点之间的最长边
这是 SQL 服务器的解决方案:
-- Find the centroid of the set of points
DECLARE @centroid_x DECIMAL(18,6);
DECLARE @centroid_y DECIMAL(18,6);
SET @centroid_x = (SELECT AVG(x) FROM points);
SET @centroid_y = (SELECT AVG(y) FROM points);
-- Find the furthest vertex from the centroid
DROP TABLE IF EXISTS #furthest_point;
SELECT
x, y
INTO #furthest_point
FROM (
SELECT
points.x,
points.y,
ROW_NUMBER() OVER (ORDER BY SQRT((points.x - @centroid_x)^2 + (points.y - @centroid_y)^2) DESC) AS rn
FROM points
) fp
WHERE fp.rn = 1;
-- Find the longest edge between the furthest vertex and any other vertex
SELECT
MAX(
SQRT(
POWER(fp.x - p.x, 2) + POWER(fp.y - p.y, 2)
)
) AS maximum_distance
FROM points p
CROSS JOIN furthest_point fp;