2017-02-22 99 views
0

項目表

PID ProjectName Phase PhaseName Price 
16-A XYZ   1  Phase 1 $500 
16-A XYZ   2  Phase 2 $500 
16-A XYZ   3  Phase 3 $500 
17-A ZYX   1  Phase 1 $250 
17-A ZYX   2  Phase 2 $250 

我想所需的輸出像下面

PID ProjectName Phase PhaseName Price 
16-A XYZ   1  Phase 1 $500 
16-A XYZ   2  Phase 2 0 
16-A XYZ   3  Phase 3 0 
17-A ZYX   2  Phase 2 $250 
17-A ZYX   3  Phase 3 0 

就像你在上面的表格所需的輸出樣本看,我想展示的一次變化,因爲$基本上PID的成本是500美元,但該PID有3個變體名稱。因此,對於每個變體多次都會顯示成本報告中的額外金額。 什麼是過濾這個最好的方法?

回答

1

如果價格始終是相同的,總有一個Phase 1,則:

select 
    PID 
    , ProjectName 
    , Phase 
    , PhaseName 
    , Price = case when Phase = 1 then Price else 0 end 
from t 

如果沒有總是Phase 1,那麼我們可以得到price每個PID的第一個實例使用row_number()像這樣:

select 
    PID 
    , ProjectName 
    , Phase 
    , PhaseName 
    , Price = case when rn = 1 then Price else 0 end 
from (
    select * 
    , rn = row_number() over (
     partition by PID 
     order by Phase 
     ) 
    from t 
) as r 
+0

這個工作對我來說,只有當我認爲有永遠是每個PID第1階段,但這裏的PID調節階段3或2,3階段或1,2階段,3 – vap0991

0

所有你需要的是:

select 
     PID 
     ,ProjectName 
     ,Phase 
     ,PhaseName 
     ,case when (lag(Price,1) over (partition by PID order by Phase)) = Price 
      then 0 else Price end as Price 
    from project 

就這麼簡單。你結束了......

enter image description here

+1

你應該改變這個'按照階段的PID順序進行分區。如果兩個項目具有相同的價格,則您的代碼也會將新項目的價格清零。 http://rextester.com/SSREC47137 – SqlZim

+0

優點,@SqlZim - 修正 –