与上滚合并工作不正常(mysql)

slwdgvem  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(489)

我正在尝试合并汇总(针对年度收入),汇总计算正确,但是没有在表格末尾输入“总计”,而是再次输入“socks”。
你知道我做错了什么吗?

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'
'白色外套','94.97'
“袜子”,“109.94”
“紧身牛仔裤”,“73.96”
'迷你裙','31.98'
'白色外套','74.97'
“黑色西装”,“40.99”
'短裤','19.98'
'迷你裙','85.96'
“喇叭裤”,“33.98”
“袜子”,“7.98”
“袜子”,“842.55”

mkshixfv

mkshixfv1#

这是因为您是按 MONTH(order_data) ,不是 product_name . 什么时候 WITH ROLLUP 在这种情况下,由替换的是grouped by column值 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)

相关问题