合并未按预期工作(mysql)

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

我试着写一个月销售额和利润的明细表,而coalesce函数并没有像预期的那样工作,也就是说,没有按我想要的方式更改null。
这是我的密码:

  1. SELECT coalesce (extract(month from o.order_date),'Total year') AS mois,
  2. sum(op.selling_price * op.quantity) AS 'Monthly sales',
  3. sum(op.selling_price * op.quantity) - sum(p.buying_price * op.quantity) AS 'Monthly Profit',
  4. count(r.return_id)
  5. FROM order_products op
  6. JOIN orders o
  7. ON o.order_id = op.order_id
  8. LEFT JOIN returns r
  9. ON r.order_product_id = op.order_product_id
  10. JOIN products p
  11. ON p.product_id = op.product_id
  12. WHERE extract(year from o.order_date) = '2016'
  13. GROUP BY mois
  14. WITH ROLLUP;

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

3xiyfsfu

3xiyfsfu1#

将使用rollup的查询放入子查询中,然后使用 COALESCE 在主查询中。

  1. SELECT COALESCE(mois, 'Total year') AS mois, `Monthly sales`, `Monthly Profit`, return_count
  2. FROM (
  3. SELECT extract(month from o.order_date) AS mois,
  4. sum(op.selling_price * op.quantity) AS 'Monthly sales',
  5. sum(op.selling_price * op.quantity) - sum(p.buying_price * op.quantity) AS 'Monthly Profit',
  6. count(r.return_id) AS return_count
  7. FROM order_products op
  8. JOIN orders o
  9. ON o.order_id = op.order_id
  10. LEFT JOIN returns r
  11. ON r.order_product_id = op.order_product_id
  12. JOIN products p
  13. ON p.product_id = op.product_id
  14. WHERE extract(year from o.order_date) = '2016'
  15. GROUP BY mois
  16. WITH ROLLUP) AS x
展开查看全部

相关问题