目前是從1開始跑
一個個比對
跑到目標數量
但是速度非常慢
有沒有更好寫法呢?
底下是目前寫法+測試資料
"pro" 資料表是存放"料號","庫存量"
"relate" 資料表是存放樹狀資料和組成數量
CREATE TABLE relate(
id nvarchar(20),
parentid nvarchar(20),
mount int
);
CREATE TABLE pro(
id nvarchar(20),
stock int
);
INSERT INTO relate (id,parentid,mount)
VALUES ('1-1', '1',1),('1-2', '1',1),('1-3', '1',1)
INSERT INTO pro (id,stock)
VALUES ('1-1',1500),('1-2',11793),('1-3',1934)
CREATE FUNCTION vr_stock(@pno as nvarchar(20))
RETURNS nvarchar(20)
BEGIN
declare @count int
set @count = 1
WHILE NOT EXISTS(
select a.Id,a.ParentId,a.mount,b.stock
from relate a
left join pro b on a.Id = b.id
where a.parentid = @pno
and (a.mount * @count) > b.stock
)
BEGIN
SET @count = @count + 1
END
RETURN @count - 1
END
select dbo.vr_stock('1')
會出現答案1500
但資料多速度會很慢
CREATE TABLE relate(
id varchar(5),
parentid varchar(5),
mount int
);
CREATE TABLE pro(
id varchar(5),
stock int
);
INSERT INTO relate (id,parentid,mount)
VALUES ('1-1', '1',1),('1-2', '1',1),('1-3', '1',1);
INSERT INTO pro (id,stock)
VALUES ('1-1',1500),('1-2',11793),('1-3',1934);
with t1 as (
select a.Id,a.ParentId,a.mount,b.stock, floor(b.stock / a.mount) as "prod"
from relate a
left join pro b on a.Id = b.id
where a.parentid = '1'
)
select min(prod)
from t1;
min
----
1500
修改成用 floor() !