postgres LAG()使用错误的先前值

时间:2018-12-26 04:59:36

标签: postgresql window-functions

获取以下数据和查询:

create table if not exists my_example(a_group varchar(1)
                        ,the_date date
                        ,metric numeric(4,3)
                        );

INSERT INTO my_example
VALUES ('1','2018-12-14',0.514)
,('1','2018-12-15',0.532)
,('2','2018-12-15',0.252)
,('3','2018-12-14',0.562)
,('3','2018-12-15',0.361);

select
    t1.the_date
    ,t1.a_group
    ,t1.metric AS current_metric
    ,lag(t1.metric, 1) OVER (ORDER BY t1.a_group, t1.the_date) AS previous_metric
from
    my_example t1;

将产生以下结果:

+------------+---------+----------------+-----------------+
|  the_date  | a_group | current_metric | previous_metric |
+------------+---------+----------------+-----------------+
| 2018-12-14 |       1 | 0.514          | NULL            |
| 2018-12-15 |       1 | 0.532          | 0.514           |
| 2018-12-15 |       2 | 0.252          | 0.532           |
| 2018-12-14 |       3 | 0.562          | 0.252           |
| 2018-12-15 |       3 | 0.361          | 0.562           |
+------------+---------+----------------+-----------------+

我期望单独的a_group==2行的previous_metric值为NULL。但是,如您所见,该值显示为0.532,该值是从上一行中提取的。如何修改查询以产生预期的NULL值?

1 个答案:

答案 0 :(得分:0)

您需要将LAGa_group上的分区一起使用,因为您需要特定帧的滞后值:

SELECT
    t1.the_date,
    t1.a_group,
    t1.metric AS current_metric,
    LAG(t1.metric, 1) OVER (PARTITION BY t1.a_group ORDER BY t1.the_date)
        AS previous_metric
FROM my_example t1;