Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's a couple of ways to get the resultset. If you can live with an extra column in the resultset, and the order of the columns, then something like this is a workable approach.</p> <hr> <p><strong>using user variables</strong></p> <pre><code>SELECT d.Date , IF(@prev_units IS NULL ,@diff := 0 ,@diff := d.units - @prev_units ) AS `Units_used` , @prev_units := d.units AS `Units` FROM ( SELECT @prev_units := NULL ) i JOIN ( SELECT t.Date, t.Units FROM mytable t ORDER BY t.Date, t.Units ) d </code></pre> <p>This returns the specified resultset, but it includes the Units column as well. It's possible to have that column filtered out, but it's more expensive, because of the way MySQL processes an inline view (MySQL calls it a "derived table")</p> <p>To remove that extra column, you can wrap that in another query...</p> <pre><code>SELECT f.Date , f.Units_used FROM ( query from above goes here ) f ORDER BY f.Date </code></pre> <p>but again, removing that column comes with the extra cost of materializing that result set a second time. </p> <hr> <p><strong>using a semi-join</strong></p> <p>If you are guaranteed to have a single row for each <code>Date</code> value, either stored as a DATE, or as a DATETIME with the timecomponent set to a constant, such as midnight, and no gaps in the Date value, and Date is defined as DATE or DATETIME datatype, then another query that will return the specifid result set:</p> <pre><code>SELECT t.Date , t.Units - s.Units AS Units_Used FROM mytable t LEFT JOIN mytable s ON s.Date = t.Date + INTERVAL -1 DAY ORDER BY t.Date </code></pre> <p>If there's a missing Date value (a gap) such that there is no matching previous row, then Units_used will have a NULL value.</p> <hr> <p><strong>using a correlated subquery</strong></p> <p>If you don't have a guarantee of no "missing dates", but you have a guarantee that there is no more than one row for a particular Date, then another approach (usually more expensive in terms of performance) is to use a correlated subquery:</p> <pre><code>SELECT t.Date , ( t.Units - (SELECT s.Units FROM mytable s WHERE s.Date &lt; t.Date ORDER BY s.Date DESC LIMIT 1) ) AS Units_used FROM mytable t ORDER BY t.Date, t.Units </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload