Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何检测postgres中的列是否持续增加?_Sql_Postgresql - Fatal编程技术网

Sql 如何检测postgres中的列是否持续增加?

Sql 如何检测postgres中的列是否持续增加?,sql,postgresql,Sql,Postgresql,我有一个按“类别”和“编号”排序的表。我正在尝试检测数量没有增加的行。我尝试过这种方法: WITH test AS ( SELECT * FROM ( VALUES ('A', 1), ('B', 2), ('C', 4), ('D', 3), ('F', 5), ('F', 6), ('G', 7),

我有一个按“类别”和“编号”排序的表。我正在尝试检测数量没有增加的行。我尝试过这种方法:

WITH test AS (
    SELECT * FROM (
        VALUES
            ('A', 1),
            ('B', 2),
            ('C', 4),
            ('D', 3),
            ('F', 5),
            ('F', 6),
            ('G', 7),
            ('H', 9),
            ('H', 8)
    ) AS t(category, number)
),
test_with_previous as(
select t.*, 
  lag(number) over (order by category, number) as prev_number
  from test t
)
select *
from test_with_previous
where prev_number > number;
其中:

类别 数字 上一个号码 D 3. 4. 使用超前而不是滞后:

您可以向数据中添加一个行号以获得序列号,然后与下一条记录合并,并以不等于1的增量过滤所有记录,或者您也可以简单地调整过滤器以获得所需的任何内容

;WITH 
test AS (
    SELECT * FROM (
        VALUES
            ('A', 1),
            ('B', 2),
            ('C', 4),
            ('D', 3),
            ('F', 5),
            ('F', 6),
            ('G', 7),
            ('H', 9),
            ('H', 8)
    ) AS t(category, number)
),
test_idx as (
    select *, ROW_NUMBER() over (order by category, number) id
    from test
)
select t1.id, t2.id, t1.category c1, t2.category c2, t1.number n1, t2.number n2, t2.number - t1.number diff
from test_idx t1
left join test_idx t2 on t1.id = t2.id-1
where t1.number <> t2.number -1;

好的,D是第一行,数字减少。您是否正在查找与上一行不同的第一行?
;WITH 
test AS (
    SELECT * FROM (
        VALUES
            ('A', 1),
            ('B', 2),
            ('C', 4),
            ('D', 3),
            ('F', 5),
            ('F', 6),
            ('G', 7),
            ('H', 9),
            ('H', 8)
    ) AS t(category, number)
),
test_idx as (
    select *, ROW_NUMBER() over (order by category, number) id
    from test
)
select t1.id, t2.id, t1.category c1, t2.category c2, t1.number n1, t2.number n2, t2.number - t1.number diff
from test_idx t1
left join test_idx t2 on t1.id = t2.id-1
where t1.number <> t2.number -1;
id  id  c1  c2  n1  n2  diff
2   3   B   C   2   4   2
3   4   C   D   4   3   -1
4   5   D   F   3   5   2