首页 > 解决方案 > 如何将 group_concat 与基于价格的数量总和一起使用?

问题描述

这是我的表,其中存储 id 及其数量和价格。我想根据价格计算数量。如果数量为负值,有时数量可能会显示为 0。因此,当按价格分组时,我不会显示数量下降为 0 值的价格。

id | id_item | qty | price
1    1         10    1.00
2    1         15    2.00
3    1         10    1.00
4    2         5     2.00
5    2         5     2.50
6    3         10    1.00
7    3         10    1.00
8    3         5     1.00

这是我尝试过的。

Select id_item, price, sum(qty) as total from sales group by id_item, price having total !=0;

Result
id_item | qty | price
1         20    1.00
1         15    2.00
2         5     2.00
2         5     2.50
3         10    1.00

concat 的预期结果

id_item | qty     | price
1         20,15     1.00,2.00
2         5,5       2.00.2.50
3         10        1.00

怎样才能达到如图所示的效果?</p>

标签: mysqlsqleloquent

解决方案


我认为您需要两个级别的聚合:

select id_item, group_concat(total order by price) as quantities,
       group_concat(price order by price) as prices
from (Select id_item, price, sum(qty) as total
      from sales
      group by id_item, price
      having total <> 0
     ) s
group by id_item;

推荐阅读