title: Optimize query with MAX (id)
body: <p>I have this query that shows me the last <code>id</code> by <code>id_units</code>, depending on the date.</p>
  
  <p>My query is:</p>
  
  <pre><code>SELECT max(swg.id) AS id
   FROM swg
   WHERE swg.status != 0
   AND sg.dateswg &lt;= TIMESTAMPADD(DAY,(6-WEEKDAY('2015-12-28')),'2015-12-28')
   GROUP BY swg.id_units
  ORDER BY swg.id;
  </code></pre>
  
  <p>The query returns more than 2000 records, I think that there is a way that I can performance this query.</p>
  
  <p>I am trying to performance my query like this:</p>
  
  <pre><code>SELECT id
  FROM (SELECT * FROM swg WHERE status != 0 AND dateswg &lt;= TIMESTAMPADD(DAY,(6-WEEKDAY('2015-12-28')),'2015-12-28') ORDER BY id_units, id desc) x
  GROUP BY id_units;
  </code></pre>
  
  <p>It is works, but I would like to know if there is another way to improve it</p>
  
  <p>Regard!</p>