我想取某一条记录最临近的4条记录,请大家帮给解决方案,谢谢

shoutor 2006-12-18 04:43:02
比如:

现在有编号为1、2、3、4、5、6、7、8、9、10的十条记录
与1最临近的记录为:2、3、4、5
与4最临近的记录为:2、3、5、6
与10最临近的记录为:6、7、8、9

我现在最笨的办法是一个一个对比,然后在union,请各位给一个最简便的方法
...全文
195 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
jacksom 2006-12-19
  • 打赏
  • 举报
回复
學習
yuanmu 2006-12-18
  • 打赏
  • 举报
回复
select top 4 *,
(select count(1) from # where id > t1.id and id < 86727 or id < t1.id and id > 86727 ) as x
from # t1
where id <> 86727
order by x

这样写好点。免得一时看不明白
yuanmu 2006-12-18
  • 打赏
  • 举报
回复
yuanmu 2006-12-18
  • 打赏
  • 举报
回复
order by (select count(1) from # where id > t1.id and id < 86727 or id < t1.id and id > 86727 )
这个地方写的好,没想到在 order by 中做手脚能这么方便
冷箫轻笛 2006-12-18
  • 打赏
  • 举报
回复
哦,明白了!呵呵
最接近的 <> 代码最接近的

你是要存储的物理位置最接近的吧?

create table #(id int)
insert into #
select 86715
union all select 86716
union all select 86717
union all select 86718
union all select 86719
union all select 86720
union all select 86721
union all select 86722
union all select 86723
union all select 86725
union all select 86726
union all select 86727
union all select 86730
union all select 86731
union all select 86732
union all select 86733
union all select 86734
union all select 86735
union all select 86740
union all select 86743
union all select 86746
union all select 86747
union all select 86749
union all select 86750
union all select 86751
union all select 86752
union all select 86754
union all select 86756
union all select 86757
union all select 86758
union all select 86759
union all select 86760
union all select 86761
union all select 86762
union all select 86763
union all select 86764
union all select 86766



--语句
select top 4 * from # t1
where id <> 86727
order by (select count(1) from # where id > t1.id and id < 86727 or id < t1.id and id > 86727 )
--结果
86726
86730
86725
86731
shoutor 2006-12-18
  • 打赏
  • 举报
回复
比如说,有这些编号的记录,用你的方法是不行的
86715
86716
86717
86718
86719
86720
86721
86722
86723
86725
86726
86727
86728
86730
86731
86732
86733
86734
86735
86740
86743
86746
86747
86749
86750
86751
86752
86754
86756
86757
86758
86759
86760
86761
86762
86763
86764
86766
冷箫轻笛 2006-12-18
  • 打赏
  • 举报
回复
修改一下
--与1最临近的记录为
select top 4 * from tablename where columnname <> 1 order by abs(columnname - 1)
--与4最临近的记录为
select top 4 * from tablename where columnname <> 4 order by abs(columnname - 4)


跟编号是否连续没有关系阿!
条数是什么意思?取的最临近记录条数不固定?
shoutor 2006-12-18
  • 打赏
  • 举报
回复
这是不行的,我的编号首先是不连续的,是随机的,而且条数也不固定
冷箫轻笛 2006-12-18
  • 打赏
  • 举报
回复
哦,是两个帖子
冷箫轻笛 2006-12-18
  • 打赏
  • 举报
回复
--与1最临近的记录为
select top 4 * from tablename order by abs(coluname -1)
--与4最临近的记录为
select top 4 * from tablename order by abs(coluname -4)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧