2017-08-07 61 views
0

假設我有一個表如之間的距離:得到N行

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 

該表具有的4個濃度2個亞組(該分區按id製成,訪問)。在每個組中,我想遍歷所有4個濃度並返回兩個id,根據濃度訪問最近的一個。

所以查詢將返回一個結果,像這樣的:

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

感謝

+0

你看了SQL窗口函數?您可能會這樣做的方式是根據需要使用RANK或DENSE_RANK。 – RHP

+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;