简体   繁体   English

与汇总合并无法正常工作(MySql)

[英]Coalesce with Roll Up not working correctly (MySql)

I am trying to coalesce on the roll up (against the year revenue), The roll up is calculating correctly, however instead of inputting 'Grand Total' at the end of the table, 'Socks' is being inputted again. 我正在尝试合并汇总(相对于年收入),汇总计算正确,但是,不是在表末尾输入“总计”,而是再次输入了“袜子”。

Any ideas what i am doing wrong? 任何想法我在做什么错?

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;

'Blue Shirt', '69.93' '蓝色衬衫','69 .93'

'Denim Jeans', '197.91' '牛仔牛仔裤','197.91'

'White Blazer', '94.97' 'White Blazer','94.97'

'Socks', '109.94' '袜子','109.94'

'Skinny Jeans', '73.96' 'Skinny Jeans','73 .96'

'Mini Skirt', '31.98' 迷你裙,31.98

'White Blazer', '74.97' 'White Blazer','74.97'

'Black Blazer', '40.99' 'Black Blazer','40.99'

'Shorts', '19.98' '短裤','19 .98'

'Mini Skirt', '85.96' 迷你裙,85.96

'Flare Blouse', '33.98' 'Flare女衬衫','33 .98'

'Socks', '7.98' '袜子','7.98'

'Socks', '842.55' '袜子','842.55'

The reason for this is that you are grouping by MONTH(order_data) , not product_name . 原因是您MONTH(order_data)而不是product_name分组。 When WITH ROLLUP happens, it is the grouped by column value that gets replaced by NULL . 当发生WITH ROLLUP时,被列值分组的将被NULL取代。 If you were to change your query to: 如果要将查询更改为:

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

You would see the NULL values in the month column. 您会在month列中看到NULL值。

To achieve what you want, try changing your query to this: 为了实现您想要的,请尝试将查询更改为此:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM