title: Using MySQL CASE to SUM last month and this month totals
body: <p>I have a query to generate a list of course names and totals from 2 tables. It works fine but now I'd like to get totals for this month and last month in the same query so I've added a couple of cases. The problem is that the cases are returning empty values. </p>
  
  <p>Here's my query: </p>
  
  <pre><code>$Sql = "SELECT t1.coursename, t1.id, SUM(t2.amount) AS total,
  
  CASE 
  WHEN YEAR(t2.date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(t2.date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) THEN SUM(t2.amount)
  ELSE 0 END 
  AS lastMonthTotal,      
  
  CASE
  WHEN YEAR(t2.date) = YEAR(CURRENT_DATE) AND MONTH(t2.date) = MONTH(CURRENT_DATE) THEN SUM(t2.amount) 
  ELSE 0 END 
  AS thisMonthTotal
  
  FROM t1
  LEFT JOIN t2 ON t2.courseid = t1.courseid
  WHERE $pdoCoursesString GROUP BY t1.courseid";
  </code></pre>