mysql滞后函数

qhhrdooz  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(375)

我正在编写代码以获得滞后时间和提前期。我能够成功地获得正确的超前值,但是,不正确的滞后值。代码如下:

Select t1.user_id, t1.time_period,

t1.time_period - (select t2.time_period from monthly_usage as t2
                         where t2.user_id = t1.user_id and 
                         t2.time_period < t1.time_period
                         order by t1.time_period desc LIMIT 1) as lag,
(SELECT 
            t2.time_period
        FROM
            monthly_usage as t2
        WHERE
            t2.user_id = t1.user_id
                AND t2.time_period > t1.time_period
        ORDER by t1.time_period
        LIMIT 1) AS lead

from monthly_usage as t1;

我的输出是这样的

但我希望输出如下。

我的代码有错误吗?

x7yiwoj4

x7yiwoj41#

我来纠正你的问题

select t1.user_id, t1.time_period,
       (select t2.time_period 
        from monthly_usage as t2
        where t2.user_id = t1.user_id and 
              t2.time_period < t1.time_period
              order by t2.time_period desc LIMIT 1) as lag, -- order by t2.time_period desc
....
from monthly_usage as t1;

相关问题