Mysql查询以查找值随时间的百分比变化

标签 mysql sql

我有一个表格,其中包含与用户相关的值和日期以及他投资的跟踪/单位。如下所示:

id , track_id , user_id , value  , created_at          , updated_at,
 1 ,        7 ,       7 , 310.00 , 2014-07-11 11:55:20 , 0000-00-00 00:00:00,
 2 ,        2 ,       3 , 400.00 , 2014-07-10 00:00:00 , 0000-00-00 00:00:00,
 3 ,        2 ,       3 , 300.00 , 2014-07-11 00:00:00 , 0000-00-00 00:00:00,
 4 ,        4 ,       7 , 500.00 , 2014-07-11 09:23:17 , 0000-00-00 00:00:00,

我想要一个查询来获取类似这样的结果

user_id, yield (%)

所以基本上查询会获取前 N 个,比如过去 7 天内的 3 个获利者。我在 MySql 中的数据库

最佳答案

这有点痛苦。以下查询获取前一周的最小和最大日期:

select user_id, min(created_at) as mind, max(created_at) as maxd
from table t
where created_at >= now() - interval 7 day
group by user_id;

现在,您可以使用它通过加入来获取适当的值:

select user_id, tmin.value, tmax.value
from (select user_id, min(created_at) as mind, max(created_at) as maxd
      from table t
      where created_at >= now() - interval 7 day
      group by user_id
     ) umm join
     table tmin
     on umm.user_id = tmin.user_id and umm.mind = tmin.created_at join
     table tmax
     on umm.user_id = tmax.user_id and umm.maxd = tmax.created_at;

这为您提供了进行查询的信息。像这样的东西:

select user_id, tmin.value, tmax.value,
       (tmax.value - tmin.value) / tmax.value as gain_ratio
from (select user_id, min(created_at) as mind, max(created_at) as maxd
      from table t
      where created_at >= now() - interval 7 day
      group by user_id
     ) umm join
     table tmin
     on umm.user_id = tmin.user_id and umm.mind = tmin.created_at join
     table tmax
     on umm.user_id = tmax.user_id and umm.maxd = tmax.created_at;

关于Mysql查询以查找值随时间的百分比变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725702/

相关文章:

mysql - Visual Studio 项目看不到 MySql 命名空间

mysql - 如何编写一个查询,给出所有没有蓝房子的人的名字?

php - MySQL 先按零件编号对日期进行排序

php - MySQL 使用 REGEXP 或 LIKE 来选择带有数据库别名的表名

sql - 在sql server中使用LIKE通配符进行查询

sql - 扩展存储在数据库中的对象

php - 如何允许某些用户下载 phpMyAdmin 中表的部分内容?

mysql - 作为 MySQL root 用户 : how to switch to other user without password

php - 1 周的每日平均值

mysql - * 和 的含义。在MySql中