【发布时间】:2018-12-28 07:44:46
【问题描述】:
我有一张桌子叫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 数量的产品
我有一个这样的查询:
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
【问题讨论】:
-
为什么中间有 0,0 ?有什么规定吗?
-
您的数据集中没有空值
-
@ZaynulAbadinTuhin 因为最大月份是 5(五月),并且产品 B 在第 3 个月和第 4 个月没有 trx
-
@Strawberry 产品B有空值,第3、4个月没有交易
-
这不是一回事......
标签: mysql sql database group-concat sqlfiddle