我正在尝试更新表格中的列。目标是获取当前值并从不同的表中减去该值。以下是我正在看的内容:
update LS
set LS.Quantity = (LS.Quantity -
(
select top 1 LSM.Quantity
from tblLocationStockMovement LSM
join tblLocation L on L.ID=LSM.LocationID
join tblStock S on S.ID=LSM.StockID
join tblLocationStock LS on LS.StockID=LSM.StockID
where
LSM.StockID=LS.StockID
and MoveTypeID=16
and dateadd(DAY, DATEDIFF(day,0,DateCreated),0)='2016-08-30 00:00:00.00')
)
from tblLocationStock LS
join tblLocation L on L.ID=LS.LocationID
join tblStock S on S.ID=LS.StockID
join tblLocationStockMovement LSM on LS.StockID=LSM.StockID
tblLocationStockMovement
表具有我需要从tblLocationStock
表中减去的值。它们都可以使用tblStock
加入StockID
。我希望它会减去两个表中引用的相同股票的价值。现在它只是为每个项目做相同的数字。
我最后可能不需要join
,我只是使用它来添加where
来测试特定项目,然后再为每个项目执行此操作。你知道我哪里出错吗?
编辑:感谢大卫修复我的格式。我没有太多使用这个网站,所以我不熟悉发布内容的正确方法。
Edit2:
你们三个人都有类似的想法,奇怪的是,有时有效。
以下是我现在正在运行的内容:
update LS
set LS.Quantity=(ISNULL(LS.Quantity,0)-ISNULL(LSM.Quantity,0))
from tblLocationStock LS
join tblLocation L on L.ID=LS.LocationID
join tblStock S on S.ID=LS.StockID
join tblLocationStockMovement LSM on LSM.StockID=S.ID
where L.LongDescription='Cafe'
and MoveTypeID=2
and PLU = 715
问题是结果发生了变化,我不知道为什么。
select LSM.Quantity
from tblLocationStockMovement LSM
join tblLocation L on L.ID=LSM.LocationID
join tblStock S on S.ID=LSM.StockID
where L.LongDescription='Cafe'
and PLU=715
and MoveTypeID=2
始终导致120。
select LS.Quantity
from tblLocationStock LS
join tblLocation L on L.ID=LS.LocationID
join tblStock S on S.ID=LS.StockID
where L.LongDescription='Cafe'
and PLU = 715
总是得到53.因此,您可能希望update语句的结果始终为-67。有时会这样,但有时我会得到5分,-43分或29分。这是否有理由说答案会有所不同?
答案 0 :(得分:0)
你也可以试试这个:
UPDATE LS
SET LS.Quantity = (LS.Quantity-LSM.Quantity)
FROM tblLocationStockMovement LSM
JOIN tblLocation L ON L.ID=LSM.LocationID
JOIN tblStock S ON S.ID=LSM.StockID
JOIN tblLocationStock LS ON LS.StockID=LSM.StockID
WHERE LSM.StockID=LS.StockID
AND MoveTypeID=16
AND dateadd(DAY, DATEDIFF(DAY,0,DateCreated),0)='2016-08-30 00:00:00.00')
答案 1 :(得分:0)
试试这个:
update LS
set LS.Quantity = ISNULL(LS.Quantity,0) - ISNULL(LSM.Quantity,0)
from tblLocationStock LS
join tblLocation L on L.ID=LS.LocationID
join tblStock S on S.ID=LS.StockID
join tblLocationStockMovement LSM on LS.StockID=LSM.StockID
and MoveTypeID=16
and dateadd(DAY, DATEDIFF(day,0,DateCreated),0)='2016-08-30 00:00:00.00'
答案 2 :(得分:-1)
试试这个:
update LS
set LS.Quantity=LS.Quantity-LSM.Quantity
from tblLocationStock LS
join tblLocation L on L.ID=LS.LocationID
join tblStock S on S.ID=LS.StockID
join tblLocationStockMovement LSM on LS.StockID=LSM.StockID
where LSM.movetypeid=16
and LSM.datecreated = '08/30/2016'