我的表有一个 NAME 和 DISTANCE 列。我想找出一种方法来列出 N 个单位 或更少 内的所有同名姓名。即给定:
NAME DISTANCE
a 2
a 4
a 3
a 7
a 1
b 3
b 1
b 2
b 5
(假设 N = 2) 我愿意
a 2
a 4
a 3
a 1
...
...
代替 a2 a 2(因为它重复计算)
我正在尝试应用此方法来解决 customerID 的 claim 日期(存储为数字)出现在彼此周围的集群中。我希望能够标记 customerID 和在同一客户的另一次 claim 后 10 天内的 claim 日期。即 |a.claimdate - b.claimdate| <= 10.当我用这个方法的时候
WHERE a.CUSTID = b.CUSTID
AND a.CLDATE BETWEEN (b.CLDATE - 10 AND b.CLDATE + 10)
AND a.CLAIMID <> b.CLAIMID
我重复计算。 CLAIMID 是独一无二的。
最佳答案
因为您不需要文本,只需要值,您可以使用 DISTINCT
来完成:
select distinct t.name, t.distance
from yourtable t
join yourtable t2 on t.name = t2.name
and (t.distance = t2.distance+1 or t.distance = t2.distance-1)
order by t.name
鉴于您的编辑,如果您要查找特定距离之间的结果,您可以使用 >= 和 <=(或 BETWEEN):
select distinct t.name, t.distance
from yourtable t
join yourtable t2 on t.name = t2.name
and t.distance >= t2.distance-1
and t.distance <= t2.distance+1
and t.distance <> t2.distance
order by t.name
您需要添加 t.distance <> t2.distance
的最终条件因此您不会返回整个数据集——从技术上讲,每个距离都在其自身之间。如果你有一个主键添加到连接中会更好,但如果你没有,你可以利用 ROW_NUMBER()
以及达到相同的结果。
with cte as (
select name, distance, row_number() over (partition by name order by (select null)) rn
from yourtable
)
select distinct t.name, t.distance
from cte t
join cte t2 on t.name = t2.name
and t.distance >= t2.distance-1
and t.distance <= t2.distance+1
and t.rn <> t2.rn
order by t.name
关于mysql - 与他人保持特定距离进入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469628/