postgresql 查找至少连续出现三次的所有数字|有没有办法用窗口函数来实现呢?

j2qf4p5b  于 2023-02-12  发布在  PostgreSQL
关注(0)|答案(3)|浏览(209)

找出至少连续出现三次的所有数字:我正在寻找一个使用窗口函数而不是进行自连接来实现此结果的查询
日志表:

+----+-----+
| Id | Num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+

结果表:

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

以下是我疑问:

select distinct l1.num as ConsecutiveNums from logs l1
inner join logs l2 on l1.id = l2.id - 1
inner join logs l3 on l1.id = l3.id + 1
where l1.num = l2.num and l2.num = l3.num

但我希望使用窗口函数代替

xqnpmsa8

xqnpmsa81#

你可以使用lag()来获取“前一行”和前一行的值。如果它们都等于当前行的值,那么你就得到了一个匹配。连续的大于3的相等数字会像这样匹配多次。重复这样的连续序列也会这样做。你可以使用DISTINCT来只选择它们一次。

SELECT DISTINCT
       num
       FROM (SELECT num,
                    lag(num, 1) OVER (ORDER BY id) = num
                    AND lag(num, 2) OVER (ORDER BY id) = num c3
                    FROM logs) x
       WHERE c3;

db<>fiddle

c2e8gylq

c2e8gylq2#

您也可以使用ROW_NUMBER()以这种方式对连续数字进行分组。

SELECT num as ConsecutiveNums 
FROM (
    SELECT *, 
           (row_number() OVER (ORDER BY id) - row_number() OVER (PARTITION BY num ORDER BY id)
            ) AS grp
    FROM logs
    ) SQ
GROUP BY num,grp
HAVING count(*) >= 3
ejk8hzay

ejk8hzay3#

SELECT num as ConsecutiveNums 
FROM (
    SELECT *, 
           row_number() OVER (ORDER BY id) - row_number() OVER (PARTITION BY num ORDER BY id as rw
    FROM table
    ) S
GROUP BY num,rw
HAVING count(*) >= 3

相关问题