2017-04-04 70 views
0

我有以下數據集:排名基於不同列的條件的PostgreSQL 8.0.2

id | date | state 
----------------------- 
    1 | 01/01/17 | high 
    1 | 02/01/17 | high 
    1 | 03/01/17 | high 
    1 | 04/01/17 | miss 
    1 | 05/01/17 | high 
    2 | 01/01/17 | miss 
    2 | 02/01/17 | high 
    2 | 03/01/17 | high 
    2 | 04/01/17 | miss 
    2 | 05/01/17 | miss 
    2 | 06/01/17 | high 

我要創造,使用PostgreSQL 8.0.2版(紅移兼容),列rank_state其中排名內id,條目按增加date(從0級開始),其中state「miss」。此外,如果條目具有「未命中」的state,則排名重複。輸出應看起來像:

id | date | state | rank_state 
------------------------------------ 
    1 | 01/01/17 | high | 0 
    1 | 02/01/17 | high | 1 
    1 | 03/01/17 | high | 2 
    1 | 04/01/17 | miss | 2 
    1 | 05/01/17 | high | 3 
    2 | 01/01/17 | miss | 0 
    2 | 02/01/17 | high | 0 
    2 | 03/01/17 | high | 1 
    2 | 04/01/17 | miss | 1 
    2 | 05/01/17 | miss | 1 
    2 | 06/01/17 | high | 2 

例如,第四行具有2的秩,因爲它是state是「未命中」,即它重複3行的秩(這同樣適用於行9和10) 。請注意,行6和7應該有秩0

我曾嘗試以下: ,(case when state is not in ('miss') then (rank() over (partition by id order by date desc) - 1) end) as state_rank,rank() over (partition by id order by case when state is not in ('miss') then date end) as state_rank 但既不給我想要的結果。任何想法都會非常有幫助。

的問題是一個類似於here,但是我想使用PostgreSQL 8.0.2版

+0

Redshift也可以使用['count()'作爲窗口函數](http://docs.aws.amazon.com/redshift/latest/dg/r_WF_COUNT.html)。你有沒有嘗試原始的答案?如果失敗,錯誤是什麼? – pozs

+0

@pozs感謝您的回覆。是的,我嘗試了原始響應 - 我得到以下錯誤:錯誤:具有ORDER BY子句的聚合窗口函數需要一個框架子句。 – labrynth

+0

是的,[紅移略有不同](http://docs.aws.amazon.com/redshift/latest/dg/r_Window_function_synopsis.html)。你需要'無界前置和當前行之間的行'(在'ORDER BY'子句之後) - 這是PostgreSQL中默認使用'ORDER BY'時的默認值,所以通常省略 – pozs

回答

0

你只需要frame_clause添加到原來的答案,因爲紅移需要它來計算的解決方案:

select * 
    , GREATEST(COUNT(case when state != 'miss' then 1 else null end) 
      OVER(PARTITION BY id order by date rows between unbounded preceding and current row) -1 , 0) as state_rank 
from tbl;