1

我编写了一个 SQL 查询,它根据库存中每种产品的剩余数量将产品分配给客户。

即如果 OurQty = 55 并且有 5 个客户(客户 1 = 35,客户 2 = 10,客户 3 = 3,客户 4 = 16,客户 5 = 6)有 70 个未完成的订单,那么我的 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”的情况下查询表时会出现问题,因为该表包含多个“PartNum”,这会影响用于检查是否(OurQty < CumulativeSum)的“CumulativeSum”的准确性,因此会阻止库存分配它在物理上并不存在。

我最初的想法是迭代地将“PartNum”作为给定“PONum”的参数传递给数据库表,然后将结果合并到我的应用程序的一个数据集中。不幸的是,我正在使用的调用 SQL 查询的程序无法将“PartNum”作为参数传递给 SQL 查询。

因此,是否可以使用 SQL 计算表中每个 PartNum 的累积和?

我正在使用 Microsoft SQL Server 2012

4

0 回答 0