2013-10-08 16 views
6

Ho la seguente query MySQL:MySQL Rollup Puzzle

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 

che restituisce:

enter image description here

Come si può vedere da sopra il totale ROLLUP in basso mostra un descrption del membership_type campo dell'ultima riga restituita. C'è un modo per sostituire questo con la parola Totale?

+1

fredda non sapeva di 'ROLLUP' – Neal

+0

Nope. Non esiste questa opzione nella sintassi mysql. Dovrai rilevare il duplicato del nome, a condizione che l'istanza FIRST del campo arrotolato sia il valore originale e che il valore successivo sia il rollup. –

+1

in base alla documentazione, quel valore di cella dovrebbe essere 'NULL'. Qui c'è qualcosa di strano. http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html –

risposta

1

Usa IFNULL per questo:

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

... 
GROUP BY membership_type With ROLLUP 

Questo non fa quello che ti serve. Se venivano totalmente ANSI compatibile, utilizza

GROUP BY members_categories.category_desc With ROLLUP 

Se si utilizza più di un elemento nella clausola GROUP BY, è necessario gestire tutti con IFNULL. Ad esempio, dal tuo 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 
+0

Grazie. Ho appena provato e ottenuto lo stesso risultato. Qualcosa di strano succedendo Penso che –

+0

questo funziona che ho provato sul mio computer locale –

+0

Per qualche motivo non funziona assolutamente qui - non ho idea del perché. Potrebbe essere qualcosa a che fare con i dati? –