X Y 字段里面有很多数据 数据为坐标 而这个坐标代表一个人的位置人有N个,求谁离第0,0最近,然后在求谁离求出的第1个最近,就这样循环下去,说白了就是找谁离谁最近然后排序出来
应该是要存储过程 我对SQL不熟啊,请帮帮忙
--创建表 create table MyPosTable(myname varchar(40),x float,y float,orderid int)--初始化记录 insert into MyPosTable(myname,x,y) select 'a1',0.8,3 insert into MyPosTable(myname,x,y) select 'a2',1.2,2.3 insert into MyPosTable(myname,x,y) select 'a3',1.5,0.7 insert into MyPosTable(myname,x,y) select 'a4',2,1.3 insert into MyPosTable(myname,x,y) select 'a5',1.8,3.2 insert into MyPosTable(myname,x,y) select 'a6',2.8,1.5 --具体实现 declare @curX float,@curY float,@i int,@myname varchar(40)--记录当前离上一个最近的坐标值 set @curX=0 set @curY=0 --排序号 set @i=1 --循环判断是否还有更新完排序号的记录 while exists(select top 1 myname from MyPosTable where orderid is null) begin --求出第一个离原点最近的点 select top 1 @myname=myname,@curX=x,@curY=y from MyPosTable where orderid is null order by SQRT(SQUARE(abs(x-@curx))+SQUARE(abs(y-@cury)))
--更新序号 update MyPosTable set orderid=@i where myname=@myname --下一序号 set @i=@i+1 end
select x,y,x*x+y*y a from PRO order by a desc
你这个只是算出根号,排序不对,排序要根据最小的一个,然后再去找离她最近的一个是谁,不要X-所有X Y-所有Y然后在根号,谁最小找到谁
应该是要存储过程 我对SQL不熟啊,请帮帮忙
create table MyPosTable(myname varchar(40),x float,y float,orderid int)--初始化记录
insert into MyPosTable(myname,x,y) select 'a1',0.8,3
insert into MyPosTable(myname,x,y) select 'a2',1.2,2.3
insert into MyPosTable(myname,x,y) select 'a3',1.5,0.7
insert into MyPosTable(myname,x,y) select 'a4',2,1.3
insert into MyPosTable(myname,x,y) select 'a5',1.8,3.2
insert into MyPosTable(myname,x,y) select 'a6',2.8,1.5
--具体实现
declare @curX float,@curY float,@i int,@myname varchar(40)--记录当前离上一个最近的坐标值
set @curX=0
set @curY=0
--排序号
set @i=1
--循环判断是否还有更新完排序号的记录
while exists(select top 1 myname from MyPosTable where orderid is null)
begin
--求出第一个离原点最近的点
select top 1 @myname=myname,@curX=x,@curY=y from MyPosTable
where orderid is null
order by SQRT(SQUARE(abs(x-@curx))+SQUARE(abs(y-@cury)))
--更新序号
update MyPosTable set orderid=@i where myname=@myname
--下一序号
set @i=@i+1
end
--输出
select * from MyPosTable order by orderid