如何从mysql中的聚合中获取最后一个项目字段

时间:2018-01-30 08:02:49

标签: mysql sql subquery

我构建查询以从交易数据中获取每个项目的库存,如下所示:

id  id_item  item_name  qty  multipler no_seal  no_pallet  Activity
---------------------------------------------------------------------------
1   23       Apple      20   1         SE002    PL123      IN
2   23       Apple      5    1         SE002    PL123      IN
3   23       Apple      10   -1        SE002    PL123      OUT
4   23       Apple      15   0         SE001    PL123      CHANGE_SEAL
5   23       Apple      15   0         SE001    PL055      CHANGE_PALLET

我尝试通过查询获取该项目的当前库存

SELECT id_item, item_name, SUM(qty * multipler) AS stock_qty, MAX(no_seal), MAX(no_pallet)
FROM item_transaction
GROUP BY id_item, item_name

id_item  item_name  qty     no_seal  no_pallet
-----------------------------------------------
23       Apple      15      SE002    PL123   

但我有问题得到no_seal和no_pallet的最后状态,聚合函数MAX()它给出最大值而不是最后记录, 我可以使用子查询来获取每个项目的最大ID,但总结数百万个数据是否过度了?

我想要no_seal和no_pallet这样的商品ID 23(Apple)的结果库存

id_item  item_name  qty     no_seal  no_pallet
-----------------------------------------------
23       Apple      15      SE001    PL055   

对不起,如果我的问题不清楚,数量15来自 20(in)+ 5(in) - 10(out)+ 0(15项更改印章)+ 0(15项更改托盘)= 15

3 个答案:

答案 0 :(得分:1)

如果您想要一个库存商品的最后一个州,那么您可以使用

select id_item,
       item_name,
       no_seal,
       no_pallet,
       (select sum(qty * multipler) from item_transaction t2 where t2.id_item = t1.id_item) qty 
from item_transaction t1
where id = (
  select max(id) 
  from item_transaction t3
  where id_item = 23
)

此解决方案假定id是唯一的,您希望item_transaction具有最高id

答案 1 :(得分:1)

您可以使用与项目相关的最大ID的内部联接

  SELECT 
      , a.item_name
      , t.stock_qty
      , a.no_seal
      , a.no_pallet
  from item_transaction a 
  inner join (
  select max(id) max_id, SUM(a.qty * a.multipler)  stock_qty,  item_name
  from item_transaction
  group by item_name ) t on t.max_id = a.item_id and t.item_name = a.item_name
  group by a.item_name

答案 2 :(得分:1)

SELECT
    *
FROM
(
    SELECT id_item, item_name, SUM(qty * multipler) AS stock_qty, MAX(id) AS last_id
    FROM item_transaction
    GROUP BY id_item, item_name
)
    summary
INNER JOIN
    item_transaction
        ON  item_transaction.id = summary.last_id