点存在于圆圈中

时间:2014-01-05 15:16:48

标签: sql sql-server math geometry

让我们考虑(x,y)是一个点,然后制作某个值radius的{​​{1}}。如果我认为我有一个点r,我需要检查(a,b)是否在以(a,b)为中心的圆圈内。

如何在SQL Server中实现此目的?

1 个答案:

答案 0 :(得分:4)

测试数据

DECLARE @t TABLE (x NUMERIC(10,2), y NUMERIC(10,2), radius NUMERIC(10,2))
INSERT INTO @t
VALUES (3.5,3.5, 5.5),(20.5,20.5, 10.5), (30.5,30.5, 20.5)

<强>查询

DECLARE @p1 NUMERIC(10,2) = 5.5   --<-- Point to check
DECLARE @p2 NUMERIC(10,2) = 5.5


SELECT *, CASE WHEN POWER( @p1 - x, 2) + POWER( @p2 - y, 2) <= POWER(radius, 2)
             THEN 'Inside The Circle'
            WHEN POWER( @p1 - x, 2) + POWER( @p2 - y, 2) > POWER(radius, 2)
             THEN 'Outside the Circle' END   [Inside/Outside]
FROM @t

结果集

╔═══════╦═══════╦════════╦════════════════════╗
║   x   ║   y   ║ radius ║   Inside/Outside   ║
╠═══════╬═══════╬════════╬════════════════════╣
║ 3.50  ║ 3.50  ║ 5.50   ║ Inside The Circle  ║
║ 20.50 ║ 20.50 ║ 10.50  ║ Outside the Circle ║
║ 30.50 ║ 30.50 ║ 20.50  ║ Outside the Circle ║
╚═══════╩═══════╩════════╩════════════════════╝

由于问题已经结束,无法添加其他答案,因此我对此进行了编辑以包含使用Sql Server Geometry类型的解决方案... [使用与上面相同的数据点,加上一个在圆圈上完全演示]

Declare @t TABLE 
   (x NUMERIC(10,2), y NUMERIC(10,2), 
    radius NUMERIC(10,2))
Insert @t
Values (3.5,3.5, 5.5),(20.5,20.5, 10.5), 
       (30.5,30.5, 20.5), (-5.5, 5.5, 11.0)

-- --------------------------
Declare @pX float = 5.5    
Declare @pY float = 5.5
Declare @c geometry;
Declare @p geometry;
Select x, y, radius, 
      (geometry::Point(X, Y, 0)).STDistance(geometry::Point(@pX, @pY, 0))
From @T
Where (geometry::Point(X, Y, 0)).STDistance(geometry::Point(@pX, @pY, 0)) > radius