title: Need help on query optimization while retrive give Error server not found
body: <p>I have query which works fine but now the data is in millions so while fetch it says server not found. What I want here to compare the sale of Previous month of current month and previous month of previous month customer wise so i user group by customer_id . </p>
  
  <p>I see that removing group by query run faster but the output i want customer wise only so it has to be there. </p>
  
  <pre><code>SELECT Customer.id, 
         Customer.first_name, 
         Customer.last_name, 
         SUM(Sale.`cal_qty`) AS totPurchase, 
         Sale2.tot2 as totPurchase2 
  FROM `customers` AS Customer 
  LEFT JOIN `sales` AS Sale 
      ON Sale.customer_id = Customer.id 
  LEFT JOIN (
      SELECT s2.customer_id AS customer_id, 
             SUM(s2.cal_qty) as tot2 
      FROM sales as s2 
      WHERE s2.sale_date between '2015-07-23' 
          AND '2015-08-21' 
      GROUP BY s2.customer_id 
  ) AS Sale2 
      ON Sale.customer_id = Sale2.customer_id 
  WHERE Sale.sale_date between '2015-08-22' AND '2015-09-21' 
  GROUP BY Sale.`customer_id` 
  having totPurchase &gt; totPurchase2 
  ORDER BY totPurchase DESC 
  </code></pre>
  
  <p>Can anyone suggest me optimized query over my query. </p>
  
  <p>Thanks in advance.</p>