2016-09-21 96 views
0

我試圖在基於現有列的表中創建一個新列。在下面的例子中,我想通過「序列號」選擇「金額」順序的最大值,最小值和中間值,「人」分區sql:從另一列中僅選擇最大值,最小值,中間值,其餘值爲空

任何人都可以幫忙嗎?謝謝!

enter image description here

在逗號的數據界定。

Person,Sequence,Amount 
A,1,1908 
A,2,3896 
A,3,2726 
A,4,4730 
A,5,4174 
A,6,3156 
A,7,3360 
A,8,2439 
B,1,1768 
B,2,1967 
B,3,1841 
B,4,1534 
B,5,729 
B,6,2434 
B,7,3502 
B,8,108 

回答

1

我會這樣做使用條件聚合。你需要更多的信息來獲得的中間值:

select person, min(amount), max(amount) 
     max(case when 2 * sequence in (cnt, cnt + 1) then amount end) as middle_val 
from (select t.*, 
      count(*) over (partition by person) as cnt 
     from t 
    ) t 
group by person; 

編輯:

哦,我明白了,你想休息的空 - 不只是每人的三個值。然後:

select t.*, 
     (case when sequence in (1, floor(cnt/2), maxseq) then amount 
     end) as new_amount 
from (select t.*, 
      count(*) over (partition by person) as cnt, 
      max(sequence) over (partition by person) as maxseq 
     from t 
    ) t; 
+0

哦謝謝!感謝幫助。 :) – Jake

相關問題