mysql - MySQL排序不同的值
问题描述
我有一张下表,用于存储物品的购买和问题。
+-----------+-----+------------+----------+
| Item_name | qty | unit_price | status |
+-----------+-----+------------+----------+
| A4 | 180 | 560 | purchase |
| A4 | -15 | 560 | issue |
| A4 | -10 | 560 | issue |
| A4 | 200 | 580 | purchase |
| A4 | -25 | 580 | issue |
| A4 | -8 | 560 | issue |
+-----------+-----+------------+----------+
购买用“purchase”表示,问题用“issues”表示,状态栏中带有(-)。
然后我需要在执行价格差异操作后获得余额,如下所示:
+-----------+-----+------------+
| Item_name | qty | unit_price |
+-----------+-----+------------+
| A4 | 147 | 560 |
| A4 | 175 | 580 |
+-----------+-----+------------+
我使用以下查询来做到这一点
select item_name, sum(qty) as qty, unit_price from stock group by item_name, unit_price
但查询只输出所需输出的第一条记录,如下所示:
+-----------+-----+------------+
| Item_name | qty | unit_price |
+-----------+-----+------------+
| A4 | 147 | 560 |
+-----------+-----+------------+
我的查询可能出了什么问题?谁能帮我 ?
已编辑的查询
$this->db->select("store_item.item_name,sum(qty) as qty, unit_price");
$this->db->from('store_update_stock_details');
$this->db->join('store_update_stock', 'store_update_stock_details.update_stock_id=store_update_stock.update_stock_id');
$this->db->join('store_item', 'store_update_stock_details.item=store_item.item_id', 'right');
$this->db->where("store_update_stock.status=1 and store_item.item_id= 1");
$this->db->group_by('store_item.item_id', 'store_update_stock_details.unit_price');
解决方案
select item_name, sum(qty) as qty, unit_price from stock group by unit_price
Group by会将所有带有as的Item_name
行聚合成一行。Item_name
A4
您想要的输出包括 2 行Item_name
asA4
编辑
select item_name, sum(qty) as qty, unit_price from stock group by item_id, unit_price
更新了包含多个项目的查询,选择 id 而不是 name。
推荐阅读
- c# - 当 WPF 中的文本太长时,带有滑块的 TextBlock
- sql - SQL Server 错误操作数类型冲突:int 与日期不兼容
- azure-resource-manager - Azure 门户是否使用未记录的 ARM 功能来部署应用服务?
- tensorflow - keras模型预测只有一和零而不是概率
- javascript - 按升序排序但在javascript中保持最高?
- azure - 从 Azure Function 存储访问令牌
- r - 创建一个变量并将一个函数应用到另一个变量
- git - 如果我测试一个拉取请求构建,我是否需要在合并后运行相同的测试?
- python - 如何将日期绘制到 matplotlib
- karate - 空手道:Azuredevops:如何在 junit 结果文件中显示所有测试方法名称