合并卷起无法正常工作(MySql)

时间:2018-04-25 18:28:15

标签: mysql

我正在努力加强汇总(与年收入相比),汇总计算正确,但不是输入' Grand Total'在桌子的最后,'袜子'正在再次输入。

任何想法我做错了什么?

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'

     

' Denim Jeans',' 197.91'

     

' White Blazer',' 94.97'

     

'袜子',' 109.94'

     

'紧身牛仔裤',' 73.96'

     

'迷你短裙',' 31.98'

     

' White Blazer',' 74.97'

     

' Black Blazer',' 40.99'

     

' Shorts',' 19.98'

     

' Mini Skirt',' 85.96'

     

' Flare Blouse',' 33.98'

     

'袜子',' 7.98'

     

'袜子',' 842.55'

1 个答案:

答案 0 :(得分:1)

原因是您按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)