Search code examples
mysqlnullcoalesce

COALESCE is not working as expected (mysql)


I am trying to write a breakdown of sales and profit per month, and the coalesce function doesn't work as expected, i.e. doesn't change the NULL by what I would like to.

Here is my code:

SELECT  coalesce (extract(month from o.order_date),'Total year') AS mois, 
                sum(op.selling_price * op.quantity) AS 'Monthly sales',
                sum(op.selling_price * op.quantity) - sum(p.buying_price * op.quantity) AS 'Monthly Profit',
                count(r.return_id)
FROM order_products op
JOIN orders o
ON o.order_id = op.order_id
LEFT JOIN returns r
ON r.order_product_id = op.order_product_id 
JOIN products p
ON p.product_id = op.product_id
WHERE extract(year from o.order_date) = '2016'
GROUP BY mois
WITH ROLLUP;

When running this code, the last line (rollup) still shows 'NULL' under the column 'mois'.

Any idea about what I could have missed?

I have tried with the function ifnull but I get the same issue.

Thanks!


Solution

  • Put the query using rollup in a subquery, and use COALESCE in the main query.

    SELECT COALESCE(mois, 'Total year') AS mois, `Monthly sales`, `Monthly Profit`, return_count
    FROM (
        SELECT  extract(month from o.order_date) AS mois, 
                        sum(op.selling_price * op.quantity) AS 'Monthly sales',
                        sum(op.selling_price * op.quantity) - sum(p.buying_price * op.quantity) AS 'Monthly Profit',
                        count(r.return_id) AS return_count
        FROM order_products op
        JOIN orders o
        ON o.order_id = op.order_id
        LEFT JOIN returns r
        ON r.order_product_id = op.order_product_id 
        JOIN products p
        ON p.product_id = op.product_id
        WHERE extract(year from o.order_date) = '2016'
        GROUP BY mois
        WITH ROLLUP) AS x