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'
'Denim Jeans', '197.91'
'White Blazer', '94.97'
'Socks', '109.94'
'Skinny Jeans', '73.96'
'Mini Skirt', '31.98'
'White Blazer', '74.97'
'Black Blazer', '40.99'
'Shorts', '19.98'
'Mini Skirt', '85.96'
'Flare Blouse', '33.98'
'Socks', '7.98'
'Socks', '842.55'
The reason for this is that you are grouping by MONTH(order_data)
, not product_name
. When WITH ROLLUP
happens, it is the grouped by column value that gets replaced by 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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.