我有以下表格:
产品(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 ,但似乎没有任何工作: - )
答案 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