Mysql汇总数据的总和

时间:2016-03-22 11:29:22

标签: mysql group-by sum left-join

我有以下表格:

产品(ID,名称,价格,类别)

销售(product_id,timestamp)

我必须完成所有销售的总结:

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 |
...

我希望最后一行类似于:

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

我尝试使用 SUM() UNION ,但似乎没有任何工作: - )

1 个答案:

答案 0 :(得分:1)

您应该使用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

或者,如果您只想对最后两列进行求和,则可以使用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