如果答案在这里显而易见,请原谅我,但我已经被困了好几天;我在下面的查询不成功。
如果'零售商'报告销售数据,但不报告某一天的库存值,我想使用前一天的值更新该缺失值。
这是一个示例表:
Retailer Date ItemID Sold Inventory
Joe's 2017-10-30 00:00:00.000 111111 10 0
Joe's 2017-10-29 00:00:00.000 111111 10 999999
Mary's 2017-10-30 00:00:00.000 123123 10 0
Mary's 2017-10-29 00:00:00.000 123123 10 888888
Betty's 2017-10-30 00:00:00.000 111111 10 499990
Betty's 2017-10-29 00:00:00.000 111111 10 500000
以下是我尝试使用的查询:
SET T1.Inventory = (SELECT T2.Inventory
FROM [dbo].[TEST] T2
WHERE CAST(T2.Date AS DATE) = CONVERT(date,getDate()-2))
FROM [dbo].[TEST] T1
WHERE Inventory = '0'
答案 0 :(得分:1)
使用DATEADD功能代替getDate()-2
如果你想要今天前一天,你应该使用GetDate并减去1,而不是2。
如果您想要在同一零售商处查看记录的前一天,那么您应该使用t1.Date并确保已关联子查询:
SET T1.Inventory = (SELECT T2.Inventory
FROM [dbo].[TEST] T2
WHERE CAST(T2.Date AS DATE) = DATEADD(day,-1,CONVERT(date,T1.Date))
AND t1.Retailer=t2.Retailer
)
...
答案 1 :(得分:0)
毫无疑问,更新库存列时遇到困难的原因是该表缺少一个唯一的列,大多数人认为该列在任何数据库表中都是绝对必要的。所以我添加了一个标识列RID作为唯一的行ID。
ALTER TABLE T1 ADD RID INT IDENTITY(1,1)
DECLARE @RID INT = (SELECT MIN(RID) FROM T1 WHERE Inventory = 0)
DECLARE @INVZERO INT = (SELECT COUNT(*) FROM T1 WHERE Inventory = 0)
WHILE @INVZERO > 0
BEGIN
UPDATE T1 SET INVENTORY =
(
SELECT INVENTORY FROM T1
WHERE RETAILER = (SELECT RETAILER FROM T1 WHERE RID = @RID)
AND [DATE] = DATEADD(DAY,-1,(SELECT [DATE] FROM T1 WHERE RID = @RID))
)
WHERE RID = @RID
SET @RID = (SELECT MIN(RID) FROM T1 WHERE Inventory = 0 AND RID > @RID)
SET @INVZERO = (SELECT COUNT(*) FROM T1 WHERE Inventory = 0)
END
SELECT * FROM T1