首页 > 解决方案 > MySQL:将 GROUP_CONCAT 中的 null 替换为 0

问题描述

我有一张桌子叫trx

trx_year  trx_month  Product  number_of_trx 
2018      4          A        100
2018      5          A        300
2018      3          A        500
2018      1          A        200
2018      2          A        150
2018      5          B        400
2018      2          B        200
2018      1          B        350

我想要结果:

具有按月订购的 trx 数量的产品 asc

我有一个这样的查询:

select product,GROUP_CONCAT(number_of_trx order by trx_month)
from trx
where trx_year=2018
group by product

该查询的结果:

Product  Data
A     200,150,500,100,300
B     350,200,400

但是,我想要这样的结果:(将月份的空值替换为 0)

Product  Data
A     200,150,500,100,300
B     350,200,0,0,400

我已经尝试ifnull()coalesce()这样:(但结果和以前一样)

select product,GROUP_CONCAT(ifnull(number_of_trx,0) order by trx_month)
from trx
where trx_year=2018
group by product;

select product,GROUP_CONCAT(coalesce(number_of_trx,0) order by trx_month)
from trx
where trx_year=2018
group by product;

也许你可以帮助我,请检查http://sqlfiddle.com/#!9/f1ed4/3

标签: mysqlsqldatabasegroup-concatsqlfiddle

解决方案


生成您想要使用的所有行cross join。那将是所有产品/月份的组合。然后使用left join引入数据并group by对其进行压缩:

select p.product,
       group_concat(coalesce(trx.number_of_trx, 0) order by trx_month)
from (select distinct product from trx) p cross join
     (select distinct trx_year, trx_month
      from trx
      where trx_year = 2018
     ) yyyymm left join
     trx
     on trx.product = p.product and
        trx.trx_year = yyyymm.trx_year
        trx.trx_month = yyyymm.trx_month
group by p.product

请注意order by. group_concat()如果您希望按时间顺序排列结果,这一点非常重要。


推荐阅读