2017-06-14 77 views
0

相關聯的值假設我有下面的表:SQL:拉動與骨料

ID1,ID2,價值

對於每個ID1,可以有多於一個的ID2和對應的值,即:

a,1,5 
a,2,6 
a,3,7 

Edit: Simpler version of ask: 
How can I pull ID1, Max(ID2), Value without having to group on value (i want 
to pull the value that corresponds to the max(id2) and without having to do a second join. 

我試圖找出一種方法來提供以下內容: ID1,閔(ID2),馬克斯(ID2),以及用最小/最大ID2相關聯的值:

一,1,3,5,7

我想出的唯一辦法是沿着線的東西:

select 
a.id1, a.min_id2, a.max_id2, b.value as min_value, c.value as max_value 
from (select id1, min(id2) as min_id2, max(id2) as max_id2) from table group by 1) a 
left outer join (select id1, id2, value from table) b on a.min_id2 = b.id2 
left outer join (select id1, id2, value from table) c on a.max_id2 = c.id2 

這是一個假設的例子,但在我的數據運行此需要的非常長的時間我。希望可能有某種我不知道的快捷方式。

回答

1

如果你想在一行中您可以使用多個OLAP功能兩者最小值/最大值(但都將在一個單一的步驟來計算的解釋):

SELECT t.*, 
    -- max id2 
    Max(id2) Over (PARTITION BY id1), 
    -- and corresponding value 
    Last_Value(value) 
    Over (PARTITION BY id1 
     ORDER BY id2 
     ROWS BETWEEN Unbounded Preceding AND Unbounded Following) 
FROM table AS t 
QUALIFY -- row with min id2 
    Row_Number() 
    Over (PARTITION BY id1 
     ORDER BY id2) = 1