mysql - 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
解决方案
生成您想要使用的所有行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()
如果您希望按时间顺序排列结果,这一点非常重要。
推荐阅读
- ansible - ansible 创建本地目录(主)
- flutter - Flutter:带有表情符号的 TextField 无法正常工作
- android - 如何获取 JSON 数组的正确 URL
- css - 设置溢出后有边距:隐藏的div?
- python - djangorestframework 视图的查询参数的 DRY 验证
- c# - 如何在 EF Core 中拥有外键和其他属性的复合键?
- javascript - 如何在 react-numpad 小部件中使用 handleChange?
- php - 我如何允许用户在 php 中使用 HTACCESS 从特定网页访问下载链接
- reactjs - mapbox 图层的正确类型(打字稿)在哪里?
- flutter - Flutter,如何在导航栏下制作一个小部件