I have a table with several million locations and a table with about 100k points of interest on a SQL Server 2019 Standard. Now I'm trying to project the following logic to a query: "Show me all locations that have bus stations within a radius of 500m to 2000m" (In the future I'd like to specify an exact number of bus stations within a given radius)
My initial approach was this:
SELECT
L.ID,
COUNT(*)
FROM
dbo.Locations AS L
INNER JOIN POI AS P ON P.GeographyPoint.STDistance(L.GeographyPoint) BETWEEN 500 AND 2000
This basically works, but execution time is unacceptable for a web application and increases with distance and number of POIs. I also tried JOINing by
P.GeographyPoint.STBuffer(500).STContains(L.GeographyPoint) = 0 AND
P.GeographyPoint.STBuffer(2000).STContains(L.GeographyPoint) = 1
or Filter(L.GeographyPoint) = 1
or STIntersects(L.GeographyPoint) = 1
with slightly different but still unsatisfying results. I also tried creating a spatial index on a precalculated buffered Geography Column for 1000m radius which took an hour and created a huge index space with still poor performance.
Caching all distances of all POIs to all locations would result in about 400 billion rows, so that's no option either.
Any help is appreciated!