作為區域倉庫貨架管理員。需要根據發貨需求從不同貨架上揀貨。已知倉庫貨架明細表:[倉庫,貨架編號,庫存數量]和倉庫揀貨數量 270,請計算每個貨架的揀貨計劃,要求揀貨次數最少。
庫存表
{"區域": "A", "貨架編號": "W1", "庫存數量": 100},
{"區域": "A", "貨架編號": "W2", "庫存數量": 150},
{"區域": "A", "貨架編號": "W3", "庫存數量": 200},
{"區域": "A", "貨架編號": "W4", "庫存數量": 40},
{"區域": "A", "貨架編號": "W5", "庫存數量": 50},
{"區域": "A", "貨架編號": "W6", "庫存數量": 80},
{"區域": "A", "貨架編號": "W7", "庫存數量": 10},
考察窗口函數
要求揀貨的次數最少,也就是優先庫存數量最大的貨架來取貨,那就需要排序了,然后判斷到哪一個貨架能滿足揀貨270個數量的需求。
SQL 如下:注意是降序 desc
with data as (
SELECT 'A' AS area, 'W1' AS shelf_code, 100 AS stock_quantity
UNION ALL
SELECT 'A' AS area, 'W2' AS shelf_code, 150 AS stock_quantity
UNION ALL
SELECT 'A' AS area, 'W3' AS shelf_code, 200 AS stock_quantity
UNION ALL
SELECT 'A' AS area, 'W4' AS shelf_code, 40 AS stock_quantity
UNION ALL
SELECT 'A' AS area, 'W5' AS shelf_code, 50 AS stock_quantity
UNION ALL
SELECT 'A' AS area, 'W6' AS shelf_code, 80 AS stock_quantity
UNION ALL
SELECT 'A' AS area, 'W7' AS shelf_code, 10 AS stock_quantity
)
-- 先排序,累加求和庫存,若要揀貨次數最少,對累加庫存 <270 進行計數+1
select count(1) + 1
from (
select
area
,shelf_code,stock_quantity
,sum(stock_quantity) over(order by stock_quantity desc) as add_stock_quantity
FROM data
) t
where add_stock_quantity < 270
輸出結果:2
該文章在 2024/3/30 11:53:52 編輯過