Reputation: 93
I have the following tables:
products (id, name, price, category)
sales (product_id, timestamp)
I have to following summary of all my sales:
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 |
...
I want the last row to be something like:
| TOTAL OF ALL SALES| | 300 |1244.00 |
+-------------------+-------+-----------+--------+
I tried with SUM() and UNION, but nothing seems to be working :-)
Upvotes: 1
Views: 81
Reputation: 40481
You should use 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
Or, if you want just the two last columns to be summed you can do it with union
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
Upvotes: 1