6

我有以下 MySQL 查询:

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

返回:

在此处输入图像描述

正如您从上方看到的,底部的 ROLLUP 总计显示了返回的最后一行的成员资格类型字段的描述。有没有办法用Total这个词来代替它?

4

1 回答 1

1

为此使用 IFNULL:

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

 ...
 GROUP BY membership_type With ROLLUP

这可以满足您的需要。如果你完全符合 ANSI,你会使用

 GROUP BY members_categories.category_desc With ROLLUP

如果您在 GROUP BY 子句中使用多个项目,则需要使用 IFNULL 处理所有项目。例如,从您的 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
于 2013-10-08T15:08:16.130 回答