基于销售订单与批次过期的库存预计在手量及过期量SQL查询需求
SQL Server查询需求:按日期计算预计在手库存及过期数量
需要编写SQL Server查询语句,按日期返回未来销售完成后预计的商品在手量,以及未售出将过期的商品数量。库存按批次(lot)存储,每个批次对应过期日期,具体数据如下:
- Lot_id(50):20件,过期日期2022-12-13
- Lot_id(52):40件,过期日期2022-12-14
当前销售订单:
- 2022-12-11:10件
- 2022-12-12:20件
- 2022-12-13:25件
inventory表结构及数据
| lot_id | item_id | quantity_on_hand | lot_expiration_date |
|---|---|---|---|
| 50 | 1 | 20 | 2022-12-13 |
| 52 | 1 | 40 | 2022-12-14 |
sales表结构及数据
| order_id | item_id | order_date | order_qty |
|---|---|---|---|
| 100 | 1 | 2022-12-11 | 10 |
| 101 | 1 | 2022-12-12 | 20 |
| 102 | 1 | 2022-12-13 | 25 |
期望查询结果
按日期展示item_id、未过期在手量(Unexpired_Qty_On_Hand)、过期在手量(Expired_Qty_On_Hand):
| Date | item_id | Unexpired_Qty_On_Hand | Expired_Qty_On_Hand |
|---|---|---|---|
| 2022-12-10 | 1 | 60 | 0 |
| 2022-12-11 | 1 | 50 | 0 |
| 2022-12-12 | 1 | 30 | 0 |
| 2022-12-13 | 1 | 5 | 0 |
| 2022-12-14 | 1 | 0 | 5 |
创建并填充数据表的SQL代码
-- SQL to create tables and populate CREATE TABLE sales ( order_id int NOT NULL, item_id int NOT NULL, order_date date NOT NULL, order_quantity int NOT NULL ); INSERT INTO sales (order_id, item_id, order_date, order_quantity) VALUES (100, 1, '2022-12-11', 10), (101, 1, '2022-12-12', 20), (102, 1, '2022-12-13', 25); CREATE TABLE inventory ( lot_id int NOT NULL, item_id int NOT NULL, quantity_on_hand int NOT NULL, lot_expiration_date date NOT NULL ); INSERT INTO inventory (lot_id, item_id, quantity_on_hand, lot_expiration_date) VALUES (50, 1, 20, '2022-12-13'), (52, 1, 40, '2022-12-14');
内容的提问来源于stack exchange,提问作者Tom Sampson
相关产品推荐
相关产品推荐

