我有以下数据集:排名基于不同列的条件的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版
Redshift也可以使用['count()'作为窗口函数](http://docs.aws.amazon.com/redshift/latest/dg/r_WF_COUNT.html)。你有没有尝试原始的答案?如果失败,错误是什么? – pozs
@pozs感谢您的回复。是的,我尝试了原始响应 - 我得到以下错误:错误:具有ORDER BY子句的聚合窗口函数需要一个框架子句。 – labrynth
是的,[红移略有不同](http://docs.aws.amazon.com/redshift/latest/dg/r_Window_function_synopsis.html)。你需要'无界前置和当前行之间的行'(在'ORDER BY'子句之后) - 这是PostgreSQL中默认使用'ORDER BY'时的默认值,所以通常省略 – pozs