我编写了一个SQL查询,根据每个库存产品的剩余数量为客户分配产品。
即。如果OurQty = 55并且有70个未完成的订单分为5个客户(客户1 = 35,客户2 = 10,客户3 = 3,客户4 = 16,客户5 = 6)那么我的SQL查询将分配预留的产品数量按顺序连接每个客户,直到OurQty = 0或所有未完成的订单都已完成。
我的SQL查询:
WITH allocate
AS (SELECT rd.ponum AS PONum,
od.orderline AS OrderLine,
rd.partnum AS PartNum,
p.partdescription AS PartDescription,
od.ordernum AS OrderNum,
rd.ourqty AS OurQty,
od.number01 AS Reserved,
rd.ourqty - od.number01 AS NewOurQty,
c.custnum AS CustNum,
c.name AS Name,
( rd.ourqty - Sum(od.number01)
OVER (
ORDER BY od.ordernum) ) AS CumulativeSum
FROM dbo.rcvdtl AS rd WITH (nolock)
INNER JOIN dbo.part AS p WITH (nolock)
ON rd.partnum = p.partnum
INNER JOIN dbo.orderdtl AS od WITH (nolock)
ON rd.partnum = od.partnum
INNER JOIN dbo.orderhed AS oh WITH (nolock)
ON od.ordernum = oh.ordernum
INNER JOIN dbo.customer AS c WITH (nolock)
ON od.custnum = c.custnum
WHERE ( rd.ponum = 73 )
AND ( od.number01 > 0 )
AND ( od.openline = 1 ))
SELECT ponum,
orderline,
partnum,
partdescription,
ordernum,
ourqty,
reserved,
newourqty,
custnum,
name,
cumulativesum + reserved AS 'Left In Stock',
CASE
WHEN ( cumulativesum + reserved ) - reserved > 0 THEN reserved
ELSE ( CASE
WHEN ( cumulativesum + reserved ) > 0 THEN
( cumulativesum + reserved )
ELSE 0
END )
END AS Allocated
FROM allocate
将'PartNum'指定为参数时,此方法可以正常工作。当我在没有指定'PartNum'的情况下查询表时会出现问题,因为该表包含多个'PartNums',这会影响'CumulativeSum'的准确性,CumulativeSum用于检查是否(OurQty< CumulativeSum)并因此阻止分配没有实际存在的股票。
我最初的想法是将数据库表'PartNum'作为给定'PONum'的参数迭代地传递,然后将结果合并到我的应用程序上的一个数据集中。不幸的是,我使用的调用SQL查询的程序无法将'PartNum'作为参数传递给SQL查询。
因此,是否可以使用SQL计算表中每个PartNum的累积总和?
我正在使用Microsoft SQL Server 2012