0

我已经在这里待了几个小时,但无济于事,把头发拉了出来。

编辑:我想通过使用 1 天前的相同数据来计算每个用户的最大“收益”,从而计算整体 exp 列之间的差异

目前我正在取一行,然后根据第一行时间戳从 1 天前选择一行,然后从 2 行中减去 total_exp 列并按该结果排序,同时按 user_id 分组

SQL 小提琴:http ://sqlfiddle.com/#!2/501c8

这是我目前拥有的,但是逻辑完全错误,所以我拉了 0 个结果

SELECT rsn, ts.timestamp, @original_ts := SUBDATE( ts.timestamp, INTERVAL 1 DAY), ts.overall_exp, ts.overall_exp - previous.overall_exp AS gained_exp
    FROM tracker AS ts
INNER JOIN (
    SELECT user_id, MIN( TIMESTAMP ) , overall_exp
    FROM tracker
    WHERE TIMESTAMP >= @original_ts
    GROUP BY user_id
) previous 
    ON ts.user_id = previous.user_id
JOIN users
    ON ts.user_id = users.id
GROUP BY ts.user_id
ORDER BY gained_exp DESC
4

2 回答 2

1

您可以通过自加入来做到这一点:

select t.user_id, max(t.overall_exp - tprev.overall_exp)
from tracker t join
     tracker tprev
     on tprev.user_id = t.user_id and
        date(tprev.timestamp) = date(SUBDATE(t.timestamp, INTERVAL 1 DAY))
group by t.user_id

这里的一个关键是将时间戳转换为日期,因此比较是准确的。

于 2013-05-11T16:17:11.410 回答
1

尝试:

select u.*, max(t.`timestamp`)-min(t.`timestamp`) gain
from users u
left join tracker t 
on u.id = t.user_id and
   t.`timestamp` >= date_sub(date(now()), interval 1 day) and
   t.`timestamp` < date_add(date(now()), interval 1 day)
group by u.id
order by gain desc

SQLFiddle在这里

于 2013-05-11T16:18:36.407 回答