mysql库存事务 - 获取位置上的序列号列表

时间:2017-01-13 13:20:24

标签: mysql sql inventory-management

我的库存数据库设计包含表格stock_transactionsstock_transactions_serials。股票交易表保存仓库中的所有IN和OUT交易。每个事务都可以包含随附的序列号列表,这些记录在stock_transactions_serials中,其中index是stock_transaction_id + serial_id。

我需要撰写一个查询,列出qty>所有位置的连续出版物列表。我在这里构建了SQL小提琴,以便在http://sqlfiddle.com/#!9/520bfa/5上使用一些数据。

目前我的SQL是这样的:

SELECT
    ST.id, 
    ST.warehouse_location_id, 
    ST.product_id,
    SUM(ST.quantity) AS qty,
    STS.serials AS serials 
FROM stock_transactions ST
LEFT JOIN (
    SELECT stock_transaction_id, GROUP_CONCAT(serial_id) AS serials
    FROM stock_transactions_serials
    GROUP by stock_transaction_id
) STS ON STS.stock_transaction_id = ST.id
WHERE 
    ST.document_id = 9 
GROUP BY ST.warehouse_location_id
HAVING qty > 0

此SQL的结果不太正确。 QTY是正确的,但序列号是错误的......它没有考虑到与本文档的其他股票交易相关的序列号。

结果应该是:

地点51连续出版物:22229

地点52系列:22221,222222,22223,22224,22225

更新:只是为了让我的问题更清楚。您将5台计算机的序列号A,B,C,D,E从位置X移动到Y.现在您有5台笔记本电脑在位置Y上有序列号。接下来,您将一台笔记本电脑从位置Y移动,序列号A返回到位置X.然后是从位置X到位置Z的另一台带有串行F的笔记本电脑...我想知道在所有交易之后每个位置的笔记本电脑(以及哪些连续出版物)的数量....

UPDATE2:想要对没有连续剧的项目也有解决方案。例如,我将5个USB棒从位置A移动到位置B.然后从B到C移动2个。最后从A到C再移动2个。每个位置的数量是多少。

1 个答案:

答案 0 :(得分:1)

每个资产的当前位置可以从影响序列的最后in类型的事务中获得。您可以使用以下查询获取这些内容:

select sts.serial_id, max(st.id) as max_in_id
from stock_transactions st
inner join stock_transactions_serials sts on sts.stock_transaction_id = st.id
where st.type='In'
group by sts.serial_id

使用上述查询作为子查询,您可以将哪些资产移动到哪个仓库,同时为您提供计数(在没有未结清单的情况下)。

select st.warehouse_location_id,
       st.product_id,
       count(sts.serial_id) as qty,
       group_concat(sts.serial_id) as serials
from stock_transactions st
inner join stock_transactions_serials sts on sts.stock_transaction_id = st.id
inner join (
    select sts2.serial_id, max(st2.id) as max_in_id
    from stock_transactions st2
    inner join stock_transactions_serials sts2 on sts2.stock_transaction_id = st2.id
    where st2.type='In'
    group by sts2.serial_id) as max_ins on st.id=max_ins.max_in_id and sts.serial_id=max_ins.serial_id
group by st.warehouse_location_id, st.product_id

上述查询假设您不能为不同的产品使用相同的序列ID,这是PK stock_transaction_idserial_id字段所暗示的。