2016-12-14 76 views
0

我有下面的表格示例。我沒有列選擇,我需要填充它。這個概念是,公司爲連續兩年的新客戶或續訂客戶提供競爭獎金,所以在下面的例子中,我有兩個例子完成選擇列我需要。請注意,僅用於type = 0在Oracle中沒有拆分的前兩個連續分區的分區

customerid year id type Select 
15774 2005 104684 20 
15774 2007 118639 0 0 
15774 2007 118639 99 
15774 2011 149354 41 
15774 2013 162651 0 1 
15774 2013 162652 43 
15774 2014 171617 0 2 
15774 2014 171900 43 
15774 2015 175424 41 
15774 2015 175425 41 
15774 2015 176702 0 0 
15774 2015 176703 43 
15774 2016 178783 41 
15774 2016 181054 0 0 

23315 2014 173594 0 1 
23315 2014 173595 43 
23315 2015 176587 0 2 
23315 2015 176588 43 

22410 2013 162747 0 1 
22410 2013 165819 43 
22410 2014 168750 0 2 
22410 2014 172894 43 
22410 2015 176362 0 0 
22410 2015 177648 43 
22410 2016 178272 41 
22410 2016 182631 0 0 

23500 2013 171520 0 1 
23500 2014 175980 0 2 

任何想法

+0

爲什麼客戶15774從0開始,但其他兩個在1? –

+0

還有什麼'select'列將取決於? – GurV

+0

你有沒有試過的查詢? – Sid

回答

1

我明白了。你想要相鄰的頭兩年。這需要查找相鄰年份的期間,然後在其中列舉,全部爲type = 0

因此,lag()和一些更多的邏輯是必要的。以下列舉了所有這些年份的客戶:

select t.*, 
     (case when type = 0 and lag_group = 1 and 
        row_number() over (partition by customerid, type, lag_group order by year) <= 2 
      then row_number() over (partition by customerid, type, lag_group order by year) 
      when type = 0 then 0 
     end) as "select" 
from (select t.*, 
      sum(case when prev_year + 1 <> year then 1 else 0 end) over (partition by customerid, type order by year) as lag_group    
     from (select t.*, 
        lag(year) over (partition by customerid, type order by year) as prev_year 
      from t 
      ) t 
    ) t; 
+0

您的答案太接近,例如對於customerid 23500不起作用。請注意,如果連續3年因此必須在連續5年的差距後的前2年獲得獎金,並且在連續2年或更長的差距之後必須在差距後的第2年再次獲得獎金。 – Giorgos