首页 > 解决方案 > 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');

标签: mysql

解决方案


select item_name, sum(qty) as qty, unit_price from stock group by unit_price

Group by会将所有带有as的Item_name行聚合成一行。Item_nameA4

您想要的输出包括 2 行Item_nameasA4

编辑

select item_name, sum(qty) as qty, unit_price from stock group by item_id, unit_price

更新了包含多个项目的查询,选择 id 而不是 name。


推荐阅读