Postgresql行之间的区别

时间:2015-01-21 09:31:23

标签: postgresql row difference

我的数据:

id value
1     10
1     20
1     60
2     10
3     10
3     30

如何计算列'更改'?

id value  change  |    my comment, how to compute
1     10     10   |    20-10
1     20     40   |    60-20
1     60     40   |    default_value-60. In this example default_value=100 
2     10     90   |    default_value-10
3     10     20   |    30-10
3     30     70   |    default_value-30

换句话说:如果id行是last,那么计算100值, 否则计算next_value-value_now

2 个答案:

答案 0 :(得分:2)

您可以访问" next"的值(或"之前的#34;)行使用window function。 " next"的概念如果您有一列用于在行上定义订单,则行才有意义。您说您有一个日期列,您可以在其上订购结果。我为此使用了列名your_date_column。当然,您需要将其替换为实际的列名。

select id, 
       value, 
       lead(value, 1, 100) over (partition by id order by your_date_column) - value as change
from the_table
order by id, your_date_column

lead(value, 1, 100)说:选择" next"的value列行(1)。如果没有这样的行,请使用默认值100

答案 1 :(得分:1)

加入子查询并使用ROW_NUMBER查找每个组的最后一个值

WITH CTE AS(
SELECT id,value,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) rn,
(LEAD(value) OVER (PARTITION BY id ORDER BY date)-value) change FROM t)
SELECT cte.id,cte.value,
(CASE WHEN cte.change IS NULL THEN 100-cte.value ELSE cte.change END)as change FROM cte LEFT JOIN
(SELECT id,MAX(rn) mrn FROM cte
GROUP BY id) as x
ON x.mrn=cte.rn AND cte.id=x.id

FIDDLE