首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在值更改时查找运行合计

在值更改时查找运行合计
EN

Stack Overflow用户
提问于 2019-05-23 07:17:16
回答 1查看 20关注 0票数 0

我想要在值发生变化时获得一个运行总数。我的表有一系列的值,它们一直在变化。我需要给出输出,比如值在一个序列中重复多少次。

对于ex:假设table有两个值。

abc 0
abc 0
abc 1
abc 0
abc 0
abc 0
abc 1
abc 1
abc 0
def 1
def 1
def 0
def 1
def 0

我知道我们需要使用row_number和lag函数,但无法确定序列的确切变化时间。

abc 0   1
abc 0   2
abc 1   1
abc 0   1
abc 0   2
abc 0   3
abc 1   1
abc 1   2
abc 0   1
def 1   1
def 1   2
def 0   1
def 1   1
def 0   1
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-23 07:24:56

数据库表表示无序集合。因此,您可以做您想做的事情--假设您有一个列指定了顺序。这样的列可以是serial列或插入日期/时间或其他列。

有了这样一个专栏,这就是一个差距和孤岛问题。我认为最简单的解决方案是使用行号的差异来识别组:

select col1, col2,
       row_number() over (partition by col1, col2, (seqnum - seqnum_2) order by <ordering column>) as col3
from (select t.*,
             row_number() over (partition by col1 order by <ordering column>) as seqnum,
             row_number() over (partition by col1, col2 order by <ordering column>) as seqnum_2
      from t
     ) t;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56266158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档