2016-03-22 15 views
1

Ich habe die folgenden Tabellen:Mysql Summe von gruppierten Daten

Produkte (id, Name, Preis, Kategorie)

Umsatz (product_id, Zeitstempel)

ich folgende haben Zusammenfassung aller meiner Verkäufe:

SELECT products.name AS products, TRUNCATE(products.price/100,2) as price, 
    COUNT(*) as sales_nbr, TRUNCATE(products.price/100*COUNT(*),2) as total 
    FROM sales 
    LEFT JOIN products ON sales.product_id=products.id 
    GROUP BY product_id 
    ORDER BY products.category 

+-------------------+-------+-----------+--------+ 
| Products   | price | sales_nbr | total | 
+-------------------+-------+-----------+--------+ 
| Hot-dog   | 4.00 | 99  | 396.00 | 
| Sandwich   | 4.00 | 64  | 256.00 | 
| Croissant/brioche | 2.00 | 31  | 62.00 | 
| Frites   | 5.00 | 106  | 530.00 | 
... 

möchte ich die letzte Zeile zu sein, etwas wie:

| TOTAL OF ALL SALES|  | 300  |1244.00 | 
+-------------------+-------+-----------+--------+ 

ich mit SUM versucht() und UNION, aber nichts scheint :-)

Antwort

1

Sie sollten ROLLUP which is explain here.

SELECT products.name AS products, TRUNCATE(products.price/100,2) as price, 
    COUNT(*) as sales_nbr, TRUNCATE(products.price/100*COUNT(*),2) as total 
    FROM sales 
    LEFT JOIN products ON sales.product_id=products.id 
    GROUP BY product_id WITH ROLLUP 
    ORDER BY products.category 
verwenden zu funktionieren

Oder, wenn Sie nur die zwei letzten Spalten summiert werden möchten, können Sie es mit Union

tun
SELECT products.name AS products, TRUNCATE(products.price/100,2) as price, 
    COUNT(*) as sales_nbr, TRUNCATE(products.price/100*COUNT(*),2) as total 
    FROM sales 
    LEFT JOIN products ON sales.product_id=products.id 
    GROUP BY product_id 
UNION ALL 
SELECT 'TOTAL OF ALL SALES' , null, 
    COUNT(*) as sales_nbr, SUM(TRUNCATE(products.price/100,2)) as total 
    FROM sales 
    LEFT JOIN products ON sales.product_id=products.id 
ORDER BY products.category 
+0

Danke, Ihre zweite Lösung hat gut funktioniert :-) (außer der * ORDER BY products.category * ist aber egal) – shlagwuk