从具有较高调度数量的Id中取出数量

时间:2016-04-13 08:28:19

标签: sql-server sql-server-2012

我是新来的,我想出了一个场景,我必须从有调度的那些中取出数量。例如,我有下表

ID  SKU   QtyRec  QTYDisp
1   001A   50      0
2   001A   50      10
3   001A   50      20
4   001A   50      0

我已经取出了40个数量。它应首先从id 3然后从id 2然后从1或4中选择。因为Dispatch Quantity在3中然后在2中更大。但在我当前的场景中它从id 1中选取40。

DECLARE @Data table (Id int identity(1,1)
, SKU varchar(10)
, QtyRec INT
,QtyDis INT
)
DECLARE @Qty int = 20

INSERT @Data VALUES
('001A', 50 ,0),
('001A', 50,10 ),
('001A', 50 ,20),
('001A', 50,0)


;WITH sumqty AS 
(
    SELECT *, SUM(QtyRec) OVER (PARTITION BY SKU ORDER BY Id) AS TotalQty FROM @Data
)
,takeqty AS (
SELECT *, 
CASE 
    WHEN @Qty >= TotalQty THEN QtyRec 
    ELSE @Qty - ISNULL(LAG(TotalQty) OVER (PARTITION BY SKU ORDER BY Id), 0)
END AS TakeQty
FROM sumqty
)
SELECT * FROM takeqty WHERE TakeQty > 0

1 个答案:

答案 0 :(得分:0)

我认为您应该按QtyDis DESC订购,而不是Id ASC订购:

DECLARE @Data TABLE
    (
      Id INT IDENTITY(1, 1) ,
      SKU VARCHAR(10) ,
      QtyRec INT ,
      QtyDis INT
    )
DECLARE @Qty INT = 70

INSERT  @Data
VALUES  ( '001A', 50, 0 ),
        ( '001A', 50, 10 ),
        ( '001A', 50, 20 ),
        ( '001A', 50, 0 );
WITH    sumqty
          AS ( SELECT   * ,
                        SUM(QtyRec - QtyDis) OVER ( PARTITION BY SKU ORDER BY QtyDis DESC, Id ) AS TotalQty
               FROM     @Data
             ),
        takeqty
          AS ( SELECT   * ,
                        CASE WHEN @Qty > TotalQty THEN TotalQty
                             ELSE @Qty
                                  - ISNULL(LAG(TotalQty) OVER ( PARTITION BY SKU ORDER BY QtyDis DESC, Id ),
                                           0)
                        END AS TakeQty
               FROM     sumqty
             )
    SELECT  *
    FROM    takeqty
    WHERE   TakeQty > 0

输出:

Id  SKU     QtyRec  QtyDis  TotalQty    TakeQty
3   001A    50      20      30          30
2   001A    50      10      70          40