合并未按预期工作(mysql)

d6kp6zgx  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(295)

我试着写一个月销售额和利润的明细表,而coalesce函数并没有像预期的那样工作,也就是说,没有按我想要的方式更改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;

运行此代码时,最后一行(rollup)在“mois”列下仍显示“null”。
你知道我错过了什么吗?
我尝试过函数ifnull,但我得到了相同的问题。
谢谢!

3xiyfsfu

3xiyfsfu1#

将使用rollup的查询放入子查询中,然后使用 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

相关问题