gpt4 book ai didi

Mysql 分组数据求和

转载 作者:行者123 更新时间:2023-11-28 23:34:36 25 4
gpt4 key购买 nike

我有以下表格:

产品(id、名称、价格、类别)

销售额(product_id,时间戳)

我必须对我的所有销售进行以下总结:

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,但似乎没有任何效果:-)

最佳答案

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

关于Mysql 分组数据求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36153194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com