2016-12-14 71 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