title: Mysql subtracting values using row selected from min timestamp, grouping by id
body: <p>I've been at this for a few hours now to no avail, pulling my hair out.</p>
  
  <p>Edit: Im wanting to calculate the difference between the overall_exp column by using the same data from 1 day ago to calculate the greatest 'gain' for each user</p>
  
  <p>Currently I'm take a row, then select a row from 1 day ago based on the first rows timestamp then subtract the overall_exp column from the 2 rows and order by that result whilst grouping by user_id</p>
  
  <p>SQL Fiddle: <a href="http://sqlfiddle.com/#!2/501c8" rel="nofollow">http://sqlfiddle.com/#!2/501c8</a></p>
  
  <p>Here is what i currently have, however the logic is completely wrong so im pulling 0 results</p>
  
  <pre><code>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 &gt;= @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
  </code></pre>