一周中每个仓库的库存都会更新。一周从星期三(12:00:00 AM)到星期二(11:59:59 PM)开始。
如果我选择“十月”,则它有5个星期三,“ 10月2日”应具有9月25日至10月1日的数据。
代码:
CREATE TABLE WarehouseUpdate
(
WarehouseID INT
,WarehouseName VARCHAR(100)
,City VARCHAR(100)
,[State] VARCHAR(20)
,CurrentInventory INT
,ModifiedDate DATETIME2
)
SET @FromWed = DATEADD(DAY, - (DATEPART(dw, @ModifiedDate) + @@DATEFIRST - 4) % 7, @ModifiedDate);
SET @ToWed = DATEADD(DAY, - (DATEPART(dw, @ModifiedDate) + @@DATEFIRST - 4) % 7 + 7, @ModifiedDate);
INSERT INTO dbo.WarehouseUpdate
VALUES
(6541, 'XYZ','Huntsville','Alabama',658,'2019/10/07')
,(6541, 'XYZ','Huntsville','Alabama',941,'2019/10/08')
,(6417, 'ABC','Denver','Colorado',1001,'2019/09/26')
,(6541, 'XYZ','Huntsville','Alabama',745,'2019/09/29')
,(6589, 'JKL','Atlanta','Georgia',798,'2019/08/14')
/*Result should be for September 2019 (if the quantity is not updated for the warehouse, it should get CurrentInventory for last modified date), Inventory for Denver and Atlanta isn't updated after modified dates*/
For Wednesday 2nd
,(6541, 'XYZ','Huntsville','Alabama',745,'2019/09/29')
,(6417, 'ABC','Denver','Colorado',1001,'2019/09/26')
,(6589, 'JKL','Atlanta','Georgia',798,'2019/08/14')
For Wednesday 9th
(6541, 'XYZ','Huntsville','Alabama',941,'2019/10/08')
,(6417, 'ABC','Denver','Colorado',1001,'2019/09/26')
,(6589, 'JKL','Atlanta','Georgia',798,'2019/08/14')
答案 0 :(得分:1)
在@Steve的评论之后:处理此问题的典型解决方案是创建一个 calendar表。该表将保存每周(星期三至星期二)的开始和结束日期。以编程方式生成将填充表格的event.button == 2
命令应该非常容易。
insert
此表到位后,您可以简单地将create table calendar(
FromDate date primary key,
ToDate date
);
insert into calendar values
('2019-09-25', '2019-10-01'),
('2019-10-02', '2019-10-08'),
-- ... more weeks ...
;
与清单表一起使用,并使用join
仅保留每周的最新记录:
row_number()
没有日历表,您将需要动态地计算前一个星期三(使用您提供的表达式,并且看起来效果很好),并将其用作分区子句,例如:
select *
from (
select
w.*,
row_number() over(partition by c.FromDate order by w.ModifiedDate desc) rn
from calendar c
inner join WarehouseUpdate w on w.ModifiedDate between c.FromDate and c.ToDate
) x
where rn = 1