将库存平均分配给销售订单,直到SQL Server 2008中的库存为零

时间:2015-04-24 05:12:31

标签: sql-server

我有一个查询如下,结果看起来很好,但是一个问题是在划分为销售订单后,如果仍有库存,则应再次划分为填充订单数量。

DECLARE @tblOrder TABLE
     (PartCode NVARCHAR(50),
     OrderQty INT
    )
INSERT  INTO @tblOrder
        ( PartCode,
          OrderQty)
VALUES  ('A',19),
('A',1),
('B',29),
('A',13),
('D',8),
('B',3),
('A',2),
('C',10),
('A',18),
('A',20);

DECLARE @tblStock TABLE
     (PartCode NVARCHAR(50),
     StockQty INT
    )
INSERT  INTO @tblStock
        ( PartCode,
          StockQty)
VALUES  ('A',60),
        ('B',20),
        ('C',10),
        ('D',10)

;WITH ordertemp AS(
SELECT o.PartCode AS partcode,
       COUNT(o.PartCode) AS totalcount,
       SUM(o.OrderQty) AS totalqty,
       MIN(s.StockQty) AS totalstock,
       MIN(s.StockQty)/COUNT(o.PartCode) AS maxallocated
FROM @tblOrder o LEFT OUTER JOIN @tblStock s ON o.PartCode=s.PartCode
GROUP BY o.PartCode)

SELECT o.PartCode,
       ot.totalstock,
       o.OrderQty,
        CASE WHEN o.OrderQty < ot.maxallocated THEN o.OrderQty
            ELSE ot.maxallocated END 'AllocatedQty'
FROM ordertemp ot LEFT OUTER JOIN @tblOrder o ON ot.partcode=o.PartCode

结果:

PartCode    totalstock  OrderQty    AllocatedQty
A   60  19  10
A   60  1   1
A   60  13  10
A   60  2   2
A   60  18  10
A   60  20  10
B   20  29  10
B   20  3   3
C   10  10  10
D   10  8   8

PartCode'A'总库存= 60,总订单数量= 73,如上面的查询总数AllocatedQty = 43,因此它有可用库存= 17以上除以销售订单。任何想法。谢谢:))

0 个答案:

没有答案