Postgresql:选择整数列

时间:2016-02-01 11:40:11

标签: postgresql

我的问题很简单。说我有以下专栏:

order_in_group
integer
------
1
2
3
5
6
9

我希望查询结果是当前值和下一个值之间的差异大于1

value1   value2   difference
integer  integer  integer
-------  -------  -------
3        5        2
6        9        3

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:3)

试试这个:

with q(i) as (
    select unnest(array[1,2,3,5,6,9])
    )
select prev, curr, curr- prev diff
from (
    select i curr, lag(i) over (order by i) prev
    from q
    ) s
where curr > prev+ 1;

 prev | curr | diff 
------+------+------
    3 |    5 |    2
    6 |    9 |    3
(2 rows)    

答案 1 :(得分:1)

您应该只需使用LAG即可将上一行与之比较;

WITH cte AS (
  SELECT order_in_group value2,
     LAG(order_in_group) OVER (ORDER BY order_in_group) value1
  FROM mytable
)
SELECT value1, value2, value2-value1 difference
FROM cte
WHERE value2-value1 > 1;