我有一个应用程序,用户可以在其中选择一个位置并查看它与几个兴趣点 (POI) 的距离。
当我检索这些距离时,我还想检索离每个 POI 下一个最近和下一个最远的位置的 ID。例如。如果我们有 10 个位置,每个位置离某个 POI 远一英里,我想返回:POI 的名称、与该 POI 的距离、下一个最近位置的 ID 以及下一个位置的 ID最远的位置。结果集的示例行可能是:'Football Ground', '1.5', 24, 784(因为我们正在查看的位置距离足球场 1.5 英里,位置 24 是下一个最近的位置,而位置 784 是下一个最远的位置.
注意:我们正在查看的位置可能离 POI 最近或最远,在这种情况下,我们需要返回 -1 作为下一个最近或最远位置的 id,以让前端知道我们可以不要靠近或靠近。
如果可能的话,我想在一份声明中做到这一点。我创建了一个函数来计算 2 点之间的距离,并一直在应用程序中使用它:
create FUNCTION [dbo].[fnc_calc_distance]
(
@lat1 as float,
@lng1 as float,
@lat2 as float,
@lng2 as float
)
RETURNS float
AS
BEGIN
declare @result as float
select @result = (3959*acos(cos(radians(@lat2))*cos(radians(@lat1))*cos(radians(@lng1)-radians(@lng2))+sin(radians(@lat2))*sin(radians(@lat1))))
RETURN @result
END
示例表结构/数据如下:
CREATE TABLE tbl_locations(
[houseID] [int] NOT NULL,
[lat] [decimal](14, 10) not NULL,
[lng] [decimal](14, 10) not NULL)
insert into tbl_locations
values (1, 54.9834400000, -1.6314250000)
insert into tbl_locations
values (2, 54.9860420000, -1.5912680000)
insert into tbl_locations
values (3, 54.9882050000, -1.5707710000)
CREATE TABLE tbl_poi(
[ID] [int] NOT NULL,
[name] [varchar](32) NOT NULL,
[lat] [decimal](14, 10) NOT NULL,
[lng] [decimal](14, 10) NOT NULL)
insert into tbl_poi
values (1, 'Football Ground', 54.9752430000, -1.6219210000)
insert into tbl_poi
values (1, 'Train Station', 54.9898610000, -1.6047600000)
我正在使用 SQL Server 2008。
提前致谢。
克里斯