[英]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, ie doesn't change the NULL by what I would like to. 我正在尝试写每个月的销售和利润明细,并且合并功能无法按预期工作,即不会按我的意愿更改NULL。
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'. 运行此代码时,最后一行(汇总)在“ mois”列下仍显示“ NULL”。
Any idea about what I could have missed? 我可能会错过的任何想法吗?
I have tried with the function ifnull but I get the same issue. 我已经尝试过使用ifnull函数,但是遇到了同样的问题。
Thanks! 谢谢!
Put the query using rollup in a subquery, and use COALESCE
in the main query. 使用汇总将查询放在子查询中,并在主查询中使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.