我正在尝试汇总(相对于年收入)汇总,汇总正确计算,但是不是在表末尾输入“总计”,而是再次输入了“袜子”。

任何想法我在做什么错?

select coalesce(product_name, 'total') as product_name,  sum(price) as year_revenue
from orders
    join product on orders.ProductID = product.ProductID
group by month(order_data) with rollup;



  '蓝色衬衫','69 .93'
  
  '牛仔牛仔裤','197.91'
  
  'White Blazer','94.97'
  
  '袜子','109.94'
  
  'Skinny Jeans','73 .96'
  
  迷你裙,31.98
  
  'White Blazer','74.97'
  
  'Black Blazer','40.99'
  
  '短裤','19 .98'
  
  '迷你裙','85 .96'
  
  'Flare女衬衫','33 .98'
  
  '袜子','7.98'
  
  '袜子','842.55'

最佳答案

原因是您要按MONTH(order_data)而不是product_name分组。发生WITH ROLLUP时,是按列值分组的内容被NULL替换。如果要将查询更改为:

SELECT MONTH(order_data) AS month, product_name, SUM(price) AS year_revenue
FROM orders
JOIN product ON orders.ProductID = product.ProductID
GROUP BY month WITH ROLLUP


您会在NULL列中看到month值。

为了实现您想要的,请尝试将查询更改为此:

SELECT IF(month IS NULL, 'Total', product_name) AS product_name, year_revenue
FROM (SELECT MONTH(order_data) as month, product_name, SUM(price) AS year_revenue
    FROM orders
    JOIN product ON orders.ProductID = product.ProductID
    GROUP BY month WITH ROLLUP)

关于mysql - 与汇总合并无法正常工作(MySql),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50029068/

10-13 03:19