MySQL滞后功能

时间:2018-04-19 12:30:51

标签: mysql sql

我正在处理代码以获得滞后和提前期。我能够成功获得正确的潜在客户价值,但是滞后值不正确。以下是代码:

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;

我的输出看起来像这样

enter image description here

但我想要输出如下。

enter image description here

我的代码中是否有错误?

1 个答案:

答案 0 :(得分:1)

让我更正 lag

的查询
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;