Skip to content
Advertisement

Pivot Queries – trouble with SUM()

I have the following query:

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;

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:

amount     when_paid    payment_type_id
---------------------------------------
500        2013-02-02          2
400        2013-02-02          3 
250        2013-02-02          2

I want the output to look like

yy   mm   name  MedPay   Liability  WC   VA   Health
----------------------------------------------------
2013  2  Fact     750       400

Advertisement

Answer

IF(p.payment_type_id = 1,SUM(p.amount),null)

–>

SUM(IF(p.payment_type_id = 1, p.amount, 0))

Or you could change 0 to NULL. I think this would end up with a blank for the value instead of 0 (when no entries in the table have type_id=1).

Or, to get “none” displayed:

IFNULL(SUM(IF(p.payment_type_id = 1, p.amount, NULL)), 'none')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement