【问题标题】:COALESCE is not working as expected (mysql)COALESCE 没有按预期工作(mysql)
【发布时间】:2018-12-08 21:49:56
【问题描述】:

我正在尝试编写每月销售额和利润的明细,但合并功能没有按预期工作,即没有按照我的意愿更改 NULL。

这是我的代码:

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;

运行此代码时,最后一行(汇总)在“mois”列下仍显示“NULL”。

知道我可能错过了什么吗?

我尝试过使用 ifnull 函数,但遇到了同样的问题。

谢谢!

【问题讨论】:

    标签: mysql null coalesce


    【解决方案1】:

    将使用汇总的查询放在子查询中,并在主查询中使用COALESCE

    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
    

    【讨论】:

    • 我试图找到一种使用子查询的方法,但没有成功。您的解决方案完美运行。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多