PostgreSQL选择最后一组的第一项

时间:2019-03-06 06:29:18

标签: sql postgresql window-functions

我有此数据:

ID | Amount
1 | 0
2 | 0
3 | 0
4 | 0 ---> NULL

ID | Amount
1 | -1 ---> this row
2 | 0
3 | 0
4 | 0
5 | 0

ID | Amount
1 | 0
2 | 0
3 | -1 ---> this row
4 | 0
5 | 0
6 | 0
7 | 0

ID | Amount
1 | 0
2 | -1
3 | -1
4 | 0
5 | 0
6 | -1 ---> this row
7 | 0
8 | 0

ID | Amount
1 | 0
2 | -1
3 | 0
4 | 0
5 | 0
6 | -1 ---> this row
7 | -1
8 | 0

我的逻辑从头开始,然后向上移动直到我们达到第一个-1。但是,我无法为此使用SQL。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

假设您有-1个,则可以通过计算后面的0个来对它们进行分组。然后可以使用dense_rank()进行枚举:

select id, rnk
from (select t.*, dense_rank() over (partition by grp) as rnk
      from (select t.*,
                   count(*) filter (where amount = 0) over (order by id desc) as grp
            from t
           ) t
     ) t
where amount = -1 and rnk = 1
order by id
fetch first 1 row only;

要处理第一种情况,可以在这样的查询中进行合并:

select id, rnk
from t
where not exists (select 1 from t where amount = -1)
order by id
fetch first 1 row only