mysql - 如何将 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>
解决方案
我认为您需要两个级别的聚合:
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;
推荐阅读
- azure-devops - Azure DevOps 提供对路径的错误访问被拒绝
- python - 如何在numpy中重新排列ndarray中的列
- php - 一次在 2 个表中插入数据,使用表单 - PHP,PDO
- firebase - 是否有从firebase匿名登录的替代方案?
- c - 来自输入和输出文件的 UNIX 重定向 - 这也显示了输出文件中的输入内容
- python - 读取多个树莓派输入引脚的脚本
- angular - 来自组件的服务变量在 Angular 10 中显示为空
- angular - Firebase Firestore - 限制用户可以创建的产品文档数量
- python - 安装本地/个人库,以便可以直接由 python 项目导入
- c - 输入一个字符后程序无故关闭