Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Rollup Puzzle

Tags:

mysql

I have the following MySQL query:

select 
        members_categories.category_desc as 'membership_type',
    SUM( CASE payment_method WHEN 'Bank Transfer' THEN amount_paid ELSE 0 END ) AS 'Bank Transfer',
    SUM( CASE payment_method WHEN 'Cash' THEN amount_paid ELSE 0 END ) AS 'Cash', 
    SUM( CASE payment_method WHEN 'Cheque' THEN amount_paid ELSE 0 END ) AS 'Cheque', 
    SUM( CASE payment_method WHEN 'Credit Card' THEN amount_paid ELSE 0 END ) AS 'Credit Card', 
    SUM( CASE payment_method WHEN 'Direct Debit' THEN amount_paid ELSE 0 END ) AS 'Direct Debit', 
    SUM( CASE payment_method WHEN 'PayPal' THEN amount_paid ELSE 0 END ) AS 'PayPal', 
    SUM( CASE payment_method WHEN 'Salary Deduction' THEN amount_paid ELSE 0 END ) AS 'Salary Deduction', 
    SUM( CASE payment_method WHEN 'Standing Order' THEN amount_paid ELSE 0 END ) AS 'Standing Order', 
    SUM( amount_paid ) AS 'Total' 
    FROM members_main, members_categories, members_payments  
    WHERE members_categories.category_code=members_main.membership_type and members_main.contact_id=members_payments.contact_id and members_payments.payment_date between '2012-01-01' and '2013-12-31' 
     GROUP BY membership_type With ROLLUP

Which returns:

enter image description here

As you can see from above the ROLLUP total at the bottom shows a descrption of the membership_type field of the last row returned. Is there a way to replace this with the word Total?

like image 717
John Higgins Avatar asked Oct 08 '13 14:10

John Higgins


1 Answers

Use IFNULL for this:

 select 
    IFNULL(members_categories.category_desc, 'Total') as 'membership_type',

 ...
 GROUP BY membership_type With ROLLUP

This does what you need. If you were being totally ANSI compliant, you'd use

 GROUP BY members_categories.category_desc With ROLLUP

If you are using more than one item in the GROUP BY clause, you need to handle them all with IFNULL. For example, from your SqlFiddle. http://sqlfiddle.com/#!2/8818d/16/0

SELECT IFNULL(product,'GROUP TOTAL') AS product,     <--- group by term
       IFNULL(year, 'YEAR TOTAL') as year,           <--- group by term
       SUM(amount) 
  FROM test_rollup
 GROUP BY year, product WITH ROLLUP
like image 69
O. Jones Avatar answered Oct 27 '22 00:10

O. Jones