SQL Query For Total Points Within Radius of a Location

前端 未结 3 1298
醉酒成梦
醉酒成梦 2021-02-11 07:27

I have a database table of all zipcodes in the US that includes city,state,latitude & longitude for each zipcode. I also have a database table of points that each have a lat

3条回答
  •  终归单人心
    2021-02-11 08:23

    SELECT * FROM tblLocation 
        WHERE 2 > POWER(POWER(Latitude - 40, 2) + POWER(Longitude - -90, 2), .5)
    

    where the 2 > part would be the number of parallels away and 40 and -90 are lat/lon of the test point

    Sorry I didn't use your tablenames or structures, I just copied this out of one of my stored procedures I have in one of my databases.

    If I wanted to see the number of points in a zip code I suppose I would do something like this:

    SELECT 
        ParcelZip, COUNT(LocationID) AS LocCount 
    FROM 
        tblLocation 
    WHERE 
        2 > POWER(POWER(Latitude - 40, 2) + POWER(Longitude - -90, 2), .5)
    GROUP BY 
        ParcelZip
    

    Getting the total count of all locations in the range would look like this:

    SELECT 
        COUNT(LocationID) AS LocCount 
    FROM 
        tblLocation 
    WHERE 
        2 > POWER(POWER(Latitude - 40, 2) + POWER(Longitude - -90, 2), .5)
    

    A cross join may be inefficient here since we are talking about a large quantity of records but this should do the job in a single query:

    SELECT 
        ZipCodes.ZipCode, COUNT(PointID) AS LocCount 
    FROM
        Points
    CROSS JOIN 
        ZipCodes
    WHERE 
        2 > POWER(POWER(Points.Latitude - ZipCodes.Latitude, 2) + POWER(Points.Longitude - ZipCodes.Longitude, 2), .5)
    GROUP BY 
        ZipCodeTable.ZipCode
    

提交回复
热议问题