title: Pivot Queries - trouble with SUM()
body: <p>I have the following query:</p>
  
  <pre><code>select
  extract(year from p.when_paid) yyyy,
  MONTHNAME(STR_TO_DATE(extract(month from p.when_paid), '%m')) mm,
  f.name,
  IF(p.payment_type_id = 1,SUM(p.amount),null) MedPay,
  IF(p.payment_type_id = 2,SUM(p.amount),null) Liability,
  IF(p.payment_type_id = 3,SUM(p.amount),null) WC,
  IF(p.payment_type_id in (8,9),SUM(p.amount),null) VA,
  IF(p.payment_type_id = 10,SUM(p.amount),null) Health
  from services s 
  join payments p on p.service_id = s.id
  join accounts a on a.id = s.account_id
  join facilities f on f.id = a.facility_id
  GROUP BY f.name, yyyy, mm
  ORDER BY f.name ASC;
  </code></pre>
  
  <p>Right now I am able to get the table to populate but it does not sort by the payment_type. For instance it will sum all of the payments in MedPay or Liability but won't split them as a pivot table would. What would be the best way to do this? Here is the table structure:</p>
  
  <pre><code>amount     when_paid    payment_type_id
  ---------------------------------------
  500        2013-02-02          2
  400        2013-02-02          3 
  250        2013-02-02          2
  </code></pre>
  
  <p>I want the output to look like</p>
  
  <pre><code>yy   mm   name  MedPay   Liability  WC   VA   Health
  ----------------------------------------------------
  2013  2  Fact     750       400
  </code></pre>