2015-10-14 37 views
0

我有一個包含項目,週期和狀態及其週期值的表。我的目標是顯示period_leaving_approved_status列中「已批准狀態」(或顯示此狀態更改的週期)後某個項目的最後一個月過去了多少個月。例如,對於201005到201008期間 - 我需要顯示「201005」值,但對於期間201011-201012 - 「201011」值。我設法標記狀態改變的那一行,但我不知道如何將這個條件應用於下列行。我的示例查詢:如果你想要的時間跨度則是這樣的SQL如何計算自某些狀態以來已經過去了多少個月

select project, 
     max(case when status = 'Approved' then period end) as ApprovedPeriod 
from subq; 

​​

編輯:

如果

with subq as (
select 123 as project, 201002 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201003 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201004 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201005 as period, 'Pending Close' as status from dual 
union all 
select 123 as project, 201006 as period, 'Pending Close' as status from dual 
union all 
select 123 as project, 201007 as period, 'Closed' as status from dual 
union all 
select 123 as project, 201008 as period, 'Closed' as status from dual 
union all 
select 123 as project, 201009 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201010 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201011 as period, 'Closed' as status from dual 
union all 
select 123 as project, 201012 as period, 'Closed' as status from dual 
union all 
select 123 as project, 201101 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201102 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201112 as period, 'Approved' as status from dual 
union all 
select 123 as project, 201301 as period, 'Pending Close' as status from dual 
union all 
select 123 as project, 201302 as period, 'Closed' as status from dual 
union all 
select 123 as project, 201203 as period, 'Closed' as status from dual 
) 

select project, 
     period, 
     status, 
     case when lag(status, 1, null) OVER (ORDER BY period)='Approved' 
     AND lag(status, 1, null) OVER (ORDER BY period) NOT IN(status) then period end as period_leaving_approved_status 
     from subq 

回答

0

我會接近這個使用聚合您需要在所有行上累積此信息,然後使用窗口函數:

select s.*, 
     max(case when status = 'Approved' then period end) over 
      (partition b project order by period) as LastApprovedPeriod 
from subq s; 
+0

您會發現,這將只會使用最後批准的期限。但是,例如對於時間段= 201005,值應該是201004而不是201112 – user3014914

+1

@ user3014914。 。 。該問題指出:「由於某些項目最後處於'覈准狀態'」。 –

+0

@Gordon也許OP想要添加相對於期間的每行信息? – shawnt00

相關問題