Mysql查询一次查找值的百分比变化

时间:2014-07-13 18:07:49

标签: 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,获得(%)

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

2 个答案:

答案 0 :(得分:2)

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

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;

答案 1 :(得分:1)

这应该做你需要的,我返回旧/新值进行说明,你可以从选择列表中删除它们,如果你只想要用户ID和%增益 -

select x.user_id,
       x.value as new_val,
       y.value as prev_val,
       (y.value / x.value - 1) * 100 as gain_pct
  from tbl x
  join tbl y
    on x.user_id = y.user_id
 where x.created_at =
       (select max(z.created_at)
          from tbl z
         where z.user_id = x.user_id
           and z.created_at between date_sub(current_date, interval 7 day) and
               current_date)
   and y.created_at =
       (select min(z.created_at)
          from tbl z
         where z.user_id = x.user_id
           and z.created_at between date_sub(current_date, interval 7 day) and
               current_date)
order by gain_pct desc
limit 3

使用LIMIT返回前3个,5个,10个等

小提琴: http://sqlfiddle.com/#!2/037243/10/0