根据日期选择记录

时间:2015-11-14 15:39:42

标签: sql sql-server sql-server-2012

以下是我的查询,我希望从那些首先到期的SKU中选择Qty。请帮帮我怎样才能做到这一点。

DECLARE @Data table (Id int identity(1,1)
, SKU varchar(10)
, QtyRec int
, Expiry date
, Rec date)
DECLARE @Qty int = 20

INSERT @Data VALUES
('001A', 5 ,'2017-01-15','2015-11-14'),
('001A', 8 ,'2017-01-10','2015-11-14'),
('001A', 6 ,'2015-12-15','2015-11-15'),
('001A', 25,'2016-01-01','2015-11-16'),
('001A', 9 ,'2015-12-20','2015-11-17')

;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 :(得分:1)

有许多可能的结果取决于您的问题:

如果您想根据到期日期升序订购结果集,请在CTE查询结束时使用ORDER BY Expiry。或者选择热门过期:使用SELECT TOP(1) ROW_NUMBER() OVER(ORDER BY Expiry) AS 'SN'代替SELECT ROW_NUMBER() OVER(ORDER BY Expiry) AS 'SN'

DECLARE @Data table (Id int identity(1,1)
, SKU varchar(10)
, QtyRec int
, Expiry date
, Rec date)
DECLARE @Qty int = 20

INSERT @Data VALUES
('001A', 5 ,'2017-01-15','2015-11-14'),
('001A', 8 ,'2017-01-10','2015-11-14'),
('001A', 6 ,'2015-12-15','2015-11-15'),
('001A', 25,'2016-01-01','2015-11-16'),
('001A', 9 ,'2015-12-20','2015-11-17');

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 ROW_NUMBER() OVER(ORDER BY Expiry) AS 'SN'
    ,   SKU
    ,   QtyRec
    ,   Expiry
    ,   Rec
    ,   TotalQty
    ,   TakeQty
FROM takeqty WHERE TakeQty > 0
ORDER BY Expiry;