我正在开发一个库存/仓库库存跟踪系统,可以扣除(出售或使用)库存数量或将其移动到另一个仓库/地点。
这是我当前的表格(简化):
CREATE TABLE stocks
(
id text /* id of the stock */
quantity int /* original quantity when the stock is first received */
location_id int /* where stock is physically located at */
attributes jsonb /* properties of the stock like size, color, length, etc. */
created_at datetime /* self-explanatory */
);
CREATE TABLE transfers
(
id text /* transfer id */
stock_id text /* id of the stock to be transferred*/
transfer_quantity int /* how much of the original stock quantity should be transferred */
to_location_id int /* can be null, if null = used or sold, if not null = transferred to another location */
created_at datetime /* self-explanatory */
);
/*Dummy Data*/
/*stocks*/
INSERT INTO stocks(id, quantity, location_id) VALUES ('id1', 10, 1);
INSERT INTO stocks(id, quantity, location_id) VALUES ('id2', 10, 2);
/*transfers, (used or sold quantities from specific stocks) */
INSERT INTO transfers(stock_id, transfer_quantity) VALUES ('id1', 1);
INSERT INTO transfers(stock_id, transfer_quantity) VALUES ('id1', 1);
INSERT INTO transfers(stock_id, transfer_quantity) VALUES ('id2', 1);
INSERT INTO transfers(stock_id, transfer_quantity) VALUES ('id2', 2);
/*transfer some quantities of a certain stock to another location inside the warehouse */
INSERT INTO transfers(stock_id, transfer_quantity, to_location_id) VALUES ('id2', 1, 1);
我正在遵循交易方法/策略来查询股票,其中我从股票表中的原始数量中减去转移数量的总和,如下所示:
SELECT stocks.id,
stocks.location_id,
stocks.quantity,
sum(transfers.transfer_quantity) AS transferred_quantity_total,
(stocks.quantity - coalesce(sum(transfers.transfer_quantity), 0)) AS remaining_qty
FROM stocks
LEFT JOIN transfers ON transfers.stock_id = stocks.id
WHERE transfers.to_location_id IS NULL
GROUP BY stocks.id,
stocks.quantity,
stocks.location_id
HAVING (stocks.quantity - coalesce(sum(transfers.transfer_quantity), 0)) > 0 /* to only get the stocks on hand */
ORDER BY stocks.id;
问题、疑问、疑虑。
(4 个带有“id2”的库存被转移,这 4 个转移交易中的 3 个被使用或出售,其中 1 个转移与库存移动到新位置有关,所以最后我有 6 个位置 2 剩余数量,位置 1 剩余数量 1)
我的数据模型设计可能不是满足我的要求的最佳模型,如果是这样,我如何对我的数据进行建模以达到预期的结果? (能够减去已售出、已使用或移动的库存数量,并查看剩余数量 + 移动数量及其当前位置)。我还需要能够使用 WHERE 子句查询位置(包括库存移动后的新位置)。
我认为,如果我能找到一种方法来消除“股票”表中的原始数量列,我就可以实现类似分类帐的数据模型,其中与数量相关的所有内容都存储在单个表中。但同样,我不太确定如何设计这个类似分类账的交易表来满足我的用例(上述查询)。
这是一个包含相关查询和数据的 dbfiddle 实例:https://dbfiddle.uk/GgU4hLRz
我很想听听您的意见。预先感谢!
这个问题可能会被关闭,因为它很可能会通过意见来回答。然而,我建议,正如您自己所暗示的那样,我所知道的所有 WMS 所采用的通常方法都是基于账本的。
只需将每个传入或传出数量记录在不同的行中 - 即,转账将由两条记录表示,负数位于“起始”位置,正数位于“至”位置。这样,某个位置或整个仓库的可用数量只是所有条目的代数和。
# I usually use ,the "UNION ALL" This version is from postgresql.
SELECT stock_in.id,
stock_in.desc,
stock_in.date,
stock_in.time,
stock_in.qty
FROM stock_in
UNION ALL
SELECT stock_out.id,
stock_out.desc,
stock_out.date,
stock_out.time,
stock_out.qty
FROM stock_out