如何获得零钱号码? [英] How to get the change number?

查看:31
本文介绍了如何获得零钱号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

source值改变时如何增加值?
我试过 rank, dense_rank, row_number 没有成功 =(

How to increase value when source value is changed?
I have tried rank, dense_rank, row_number without success =(

id | src | how to get this?
--------
1  |  1  | 1
2  |  1  | 1
3  |  7  | 2
4  |  1  | 3
5  |  3  | 4
6  |  3  | 4
7  |  1  | 5

注意:src 保证按照您看到的顺序

NOTICE: src is guaranteed to be in this order you see

有没有简单的方法可以做到这一点?

is there simple way to do this?

推荐答案

可以通过嵌套两个窗口函数来实现——第一个获取src值是否从上一行改变,第二个总结变化的数量.不幸的是,Postgres 不允许直接嵌套窗口函数,但是您可以使用子查询解决这个问题:

You can achieve this by nesting two window functions - the first to get whether the src value changed from the previous row, the second to sum the number of changes. Unfortunately Postgres doesn't allow nesting window functions directly, but you can work around that with a subquery:

SELECT
  id,
  src,
  sum(incr) OVER (ORDER BY id)
FROM (
  SELECT
    *,
    (lag(src) OVER (ORDER BY id) IS DISTINCT FROM src)::int AS incr
  FROM example
) AS _;

(在线演示)

这篇关于如何获得零钱号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆