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