Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
交叉联接中的TOP1(SQL SERVER)_Sql_Sql Server - Fatal编程技术网

交叉联接中的TOP1(SQL SERVER)

交叉联接中的TOP1(SQL SERVER),sql,sql-server,Sql,Sql Server,我有一个表,在sql server中有子表(位置x,位置y)和父表(位置x,位置y)。我想要的是找到和每个孩子最亲近的父母。我可以用“糟糕的方式”来做,但可能有一种不使用任何循环的解决方案 这是我的密码: SELECT child.idChild, child.x, child.y, parent.idParent, parent.x, parent.y, sqrt(power(child.x - parent.x, 2) + power(child.y - pare

我有一个表,在sql server中有子表(位置x,位置y)和父表(位置x,位置y)。我想要的是找到和每个孩子最亲近的父母。我可以用“糟糕的方式”来做,但可能有一种不使用任何循环的解决方案

这是我的密码:

SELECT 
    child.idChild, child.x, child.y, 
    parent.idParent, parent.x, parent.y,
    sqrt(power(child.x - parent.x, 2) + power(child.y - parent.y, 2)) as distance
FROM 
    child
CROSS JOIN 
    parent
ORDER BY 
    idChild, distance
好的,没关系。但现在我想把父母限制在每个孩子的前1位


谢谢

一个简便的方法是使用窗口功能。要获取顶行,可以使用
行号()
秩()
。有联系时就有区别了
row_number()
只返回多个值中的一个
rank()
将返回所有值

以下是编写查询的一种方法:

select idChild, x, y, idParent, parentx, parenty
from (SELECT child.idChild, child.x, child.y, 
             parent.idParent, parent.x as parentx, parent.y as parenty,
             ROW_NUMBER() over (partition by child.idchild
                                order by power(child.x - parent.x, 2) + power(child.y - parent.y, 2)
                               ) as seqnum
      FROM child CROSS JOIN 
           parent
     ) pc
where seqnum = 1;
我从distance函数中删除了
sqrt()
,因为在查找最小的数字时不需要它