1

我在网上找到了一个仓库老化库存示例(见下面的修改代码)。如果购买 (0) 的条目类型为正而销售 (1) 为负,则一切正常。但是如果值是相反的(因为取消),那么结果将是错误的。

示例:有四个条目,其中三个是购买条目,但如您所见,第二个已被取消,这就是数量为负数的原因。在这种情况下,RemainingQty 列的总和必须为 0,但结果为 1699。

我必须在我的 SQL 查询中更改什么?

感谢您的任何建议。

DECLARE @ItemLedgerEntry TABLE
     (
       id INT IDENTITY(1, 1)  NOT NULL PRIMARY KEY ,
       ItemNo INT NOT NULL, --references another item
       Qty FLOAT NOT NULL, --quantity
       EntryType INT NOT NULL, --type=0 bought, type=1 sold
       PostingDate DATETIME NOT NULL -- transaction date
     );
     
 INSERT  @ItemLedgerEntry
         ( ItemNo, qty, EntryType, PostingDate )
 VALUES  ( 1999,  1700,  0, '10-06-2021'),
         ( 1999,  -1700, 0, '29-06-2021'),
         ( 1999,       1,  0, '03-08-2021'),
         ( 1999,      - 1,  1, '09-08-2021');

                      
WITH    Sold
          AS ( SELECT   IT.[ItemNo] ,
                        SUM(IT.Qty) AS TotalSoldQty
               FROM     @ItemLedgerEntry IT
               WHERE    It.[EntryType] =1    
               GROUP BY ItemNo            
             ),
        Bought
          AS ( SELECT   IT.* ,
                        (
                SELECT  SUM(RS.Qty)
                FROM    @ItemLedgerEntry RS
                WHERE   RS.[EntryType]  =0 AND RS.[ItemNo] = IT.[ItemNo] AND RS.[PostingDate] <= IT.[PostingDate]
                       
                        ) AS RunningBoughtQty
               FROM     @ItemLedgerEntry IT
               WHERE    IT.[EntryType] = 0 
             )
    

    SELECT  
    B.[ItemNo], 
    B.[PostingDate], 
    B.[EntryType],
    S.TotalSoldQty,
    B.RunningBoughtQty,
    B.RunningBoughtQty + S.TotalSoldQty AS RunningDifferenceQty,        
    CASE WHEN  (B.RunningBoughtQty) + (S.TotalSoldQty) <0
            THEN 0
            ELSE B.RunningBoughtQty + S.TotalSoldQty
    END AS  RunningRemainingQty,
        
    CASE  WHEN B.RunningBoughtQty + S.TotalSoldQty < 0 THEN 0 
          WHEN B.RunningBoughtQty + S.TotalSoldQty > B.Qty THEN B.Qty
             ELSE B.RunningBoughtQty + S.TotalSoldQty           
    END AS  RemainingQty

    FROM    Bought B
        inner JOIN Sold S ON B.[ItemNo] = S.[ItemNo]
4

0 回答 0