title: Calculate quantity difference per product over different timestamps
body: <p><strong><a href="https://dbfiddle.uk/?rdbms=mariadb_10.3&amp;fiddle=25ba5f4b365047ab018386e189c19268" rel="nofollow noreferrer">DB-Fiddle</a></strong></p>
  <pre><code>CREATE TABLE sales (
      id int auto_increment primary key,
      time_stamp DATE,
      product VARCHAR(255),
      sales_quantity INT
  );
  
  INSERT INTO sales
  (time_stamp, product, sales_quantity
  )
  VALUES 
  (&quot;2020-01-14&quot;, &quot;Product_A&quot;, &quot;100&quot;),
  (&quot;2020-01-14&quot;, &quot;Product_B&quot;, &quot;300&quot;),
  (&quot;2020-01-14&quot;, &quot;Product_C&quot;, &quot;600&quot;),
  
  (&quot;2020-01-15&quot;, &quot;Product_A&quot;, &quot;100&quot;),
  (&quot;2020-01-15&quot;, &quot;Product_B&quot;, &quot;250&quot;),
  (&quot;2020-01-15&quot;, &quot;Product_C&quot;, &quot;600&quot;),
  
  (&quot;2020-01-16&quot;, &quot;Product_A&quot;, &quot;130&quot;),
  (&quot;2020-01-16&quot;, &quot;Product_B&quot;, &quot;250&quot;),
  (&quot;2020-01-16&quot;, &quot;Product_C&quot;, &quot;580&quot;),
  (&quot;2020-01-16&quot;, &quot;Product_D&quot;, &quot;400&quot;),
  
  (&quot;2020-01-17&quot;, &quot;Product_A&quot;, &quot;130&quot;),
  (&quot;2020-01-17&quot;, &quot;Product_B&quot;, &quot;250&quot;),
  (&quot;2020-01-17&quot;, &quot;Product_C&quot;, &quot;900&quot;),
  (&quot;2020-01-17&quot;, &quot;Product_D&quot;, &quot;260&quot;);
  </code></pre>
  <p><strong>Expected Result:</strong></p>
  <pre><code>time_stamp   |   product      |    difference
  -------------|----------------|---------------------------
  2020-01-14   |   Product_A    |       0     (100-100)
  2020-01-14   |   Product_B    |     -50     (250-300)
  2020-01-14   |   Product_C    |       0     (600-600)
  -------------|----------------|---------------------------
  2020-01-15   |   Product_A    |      30     (130-100)
  2020-01-15   |   Product_B    |       0     (250-250)
  2020-01-15   |   Product_C    |     -20     (580-600)
  -------------|----------------|---------------------------
  2020-01-16   |   Product_A    |       0     (130-130) 
  2020-01-16   |   Product_B    |       0     (250-250)
  2020-01-16   |   Product_C    |     320     (900-580) 
  2020-01-16   |   Product_D    |    -140     (260-400)
  </code></pre>
  <hr />
  <p>I want to calculate the <code>difference</code> of the <code>sales_quantity</code> per <code>product</code> between <code>timestamps</code>. <br>
  I tried to use this query but it does not return the expected result:</p>
  <pre><code>SELECT
  t1.time_stamp,
  t1.product,
  t1.sum_sales_quantity - coalesce(lag(t1.sum_sales_quantity) over(order by t1.time_stamp, t1.product), t1.sum_sales_quantity) AS difference
  FROM (
      SELECT 
      time_stamp,
      product,
      SUM(sales_quantity) AS sum_sales_quantity
      FROM sales
      GROUP BY 1,2) t1
  ORDER BY 1,2;
  </code></pre>
  <p>How do I have to modify the query to make it work?</p>