我想要在值发生变化时获得一个运行总数。我的表有一系列的值,它们一直在变化。我需要给出输出,比如值在一个序列中重复多少次。
对于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
发布于 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;
https://stackoverflow.com/questions/56266158
复制相似问题