确定特定时间范围内的价值增长

Determine growth in value in a specific time range

给定以下数据集示例,我应该如何构造我的 SQL 查询以确定 value 是否随着时间的推移(给定查询中的时间范围)针对特定的UserId 通过返回 positive/negative 增长百分比结果或 true/false 结果

UserId timestamp value
1 1617711825 350
1 1617711829 400
1 1617711830 450
5 1617711831 560

根据上面的例子,我们可以观察到 UserId=1value 增长了一定百分比。

预期结果为:

UserId growthPercentage hasValueIncreased
1 50% 1

您可以获得第一个和最后一个值,然后进行任何您喜欢的计算。一种方法是:

select userId, value_first, value_last,
       (value_first < value_last) as is_growing,
       100 * ((value_last / value_first) - 1) as increase_percentage
from (select t.*,
             first_value(value) over (partition by userId order by timestamp) as value_first,
             first_value(value) over (partition by userId order by timestamp desc) as value_last
      from t
     ) t
group by userId, value_first, value_last;

架构和插入语句:

 create table mytable(UserId int,timestamps timestamp,value int);

 insert into mytable values(1,  FROM_UNIXTIME(1617711825),  350);
 insert into mytable values(1,  FROM_UNIXTIME(1617711829),  400);
 insert into mytable values(1,  FROM_UNIXTIME(1617711830),  450);
 insert into mytable values(5,  FROM_UNIXTIME(1617711831),  560);

查询:

 select usermin.userid, 100*(usermax.value-usermin.value)/usermin.value as growthPercentage,
 (case when usermax.value>usermin.value then 1 else 0 end)hasValueIncreased
 
 from
 (SELECT USERID, VALUE  FROM mytable where userid=1
 order by timestamps 
 limit 1) usermin
 inner join
 (SELECT USERID, VALUE  FROM mytable where userid=1
 order by timestamps desc
 limit 1) usermax
 on usermin.userid=usermax.userid
 

输出: |用户名|增长百分比 | hasValueIncreased |-----: | --------------: | ------------------: | 1 | 28.5714 | 1

db<>fiddle here