[英]COALESCE is not working as expected (mysql)
我正在嘗試寫每個月的銷售和利潤明細,並且合並功能無法按預期工作,即不會按我的意願更改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函數,但是遇到了同樣的問題。
謝謝!
使用匯總將查詢放在子查詢中,並在主查詢中使用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.