SQL-点系列之间的最大距离
对不起,如果我在其他地方错过了它,有没有办法找到点列表(x,y)之间的最大距离SQL-点系列之间的最大距离,sql,max,distance,Sql,Max,Distance,对不起,如果我在其他地方错过了它,有没有办法找到点列表(x,y)之间的最大距离 您可以交叉连接以获得所有点的组合,然后使用毕达哥拉斯定理来计算距离。不过,对于大型数据集来说,这可能效率低下 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
您可以交叉连接以获得所有点的组合,然后使用毕达哥拉斯定理来计算距离。不过,对于大型数据集来说,这可能效率低下
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交叉连接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的答案是完全正确的,但如上所述,可能会遇到大数据集的问题。为了未来读者的利益,我将发布一个对大型数据集应该有效的替代方案:
-- 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;
你有多少数据?您可以交叉连接,但在大型数据集中这将非常低效。您使用的是什么数据库?SQL Server、MySQL、PostgreSQL、Oracle?Legend,唯一的问题是SQL不接受^operator。只需将其修改为
选择top 1*,sqrt(power((a.[PointX]-b.[PointX]),2)+power((a.[PointY]-b.[PointY]),2))作为与dbo的距离。GetPoints()a Join dbo.GetPoints()b在a.locationcode>b.locationcode上按距离desc排序,它工作得非常好。非常感谢,谢谢!我已经更新为使用power
——对不起,我把语法和统计软件弄混了。