获得N行之间的距离

时间:2017-08-07 00:28:25

标签: sql sql-server

假设我有一个表格,如:

ID,visit, Concentration
1, 1, 4.0
2, 2, 2.0
3, 3, 1.5
4, 4, 5.0
5, 1, 7.0
6, 2, 1.0
7, 3, 5.0
8, 4, 12.0

该表有2个4个浓度的子组(分区由id,访问)。在每组中,我想迭代所有4个浓度并返回两个id,根据浓度访问最接近的一个。

因此查询将返回如下结果:

ID, visit, concentration
2, 2, 2.0
3, 3, 1.5
5, 1, 7.0
7, 3, 5.0

由于

1 个答案:

答案 0 :(得分:0)

您可以通过各种方式分配组。假设所有大小都相同,您可以按ID的顺序枚举访问次数。然后,我认为每对返回一行最简单:

with g as (
      select t.*, row_number() over (partition by visit order by id) as grp
      from t
     )
select *
from (select g1.id as id1, g1.visit as visit1, g1.concentration as concentration1,
             g2.id as id2, g2.visit as visit2, g2.concentration as concentration2
             row_number() over (partition by g1.grp
                                order by abs(g1.concentration - g2.concentration)
                               ) as seqnum
      from g g1 join
           g g2
           on g1.grp = g2.grp and g1.id < g2.id
     ) g
where seqnum = 1;