0

例如销售表

SlNo Inventorycode Cost Date

1.    100001       1.8   01/01/2017
2.    100002       2.3   01/01/2017
3.    100002       3.5   02/01/2017
4.    100001       2.5   03/01/2017

库存表

SlNO InventoryCode  Cost    Date
1.    100001              01/01/2017
2.    100002              01/01/2017
3.    100001              01/01/2017
4.    100002              02/01/2017
5.    100001              01/01/2017
6.    100002              03/01/2017

根据上述数据,我想将关注 ItemCode 和日期的 Salestable 的 COST 更新为 stocktable。如果关注日期没有发生销售,我想更新(StockTable)上一个日期成本的成本。

4

3 回答 3

1

您是否尝试这样做:

DECLARE @Sales TABLE
(
    [SLNo] TINYINT
   ,[Inventorycode] INT
   ,[Cost] DECIMAL(9,1)
   ,[Date] DATE
);


DECLARE @Stock TABLE
(
    [SLNo] TINYINT
   ,[Inventorycode] INT
   ,[Cost] DECIMAL(9,1)
   ,[Date] DATE
);

INSERT INTO @Sales ([SLNo], [Inventorycode], [Cost], [Date])
VALUES (1, 100001, 1.8, '01/01/2017')
      ,(2, 100002, 2.3, '01/01/2017')
      ,(3, 100002, 3.5, '02/01/2017')
      ,(4, 100001, 2.5, '03/01/2017');

INSERT INTO @Stock ([SLNo], [Inventorycode], [Date])
VALUES (1, 100001, '01/01/2017')
      ,(2, 100002, '01/01/2017')
      ,(3, 100001, '01/01/2017')
      ,(4, 100002, '02/01/2017')
      ,(5, 100001, '01/01/2017')
      ,(6, 100002, '03/01/2017');

UPDATE @Stock
SET [Cost] = DS.[Cost]
FROM @Stock A
OUTER APPLY
(
    SELECT TOP 1 B.[Cost]
    FROM @Sales B
    WHERE B.[Inventorycode] = A.[Inventorycode]
        AND B.[Date] <= A.[Date]
    ORDER BY B.[Date] DESC
) DS;

SELECT *
FROM @Stock;

在此处输入图像描述

于 2017-09-15T07:38:16.083 回答
0

我还没有测试过,但这应该可以

UPDATE stocktable
SET Cost = (
        SELECT TOP 1 Cost
        FROM SalesTable st
        WHERE st.Inventorycode = StockTable.Inventorycode
            AND st.DATE <= StockTable.DATE
        ORDER BY DATE DESC
        )
FROM StockTable

如果您可以共享架构和数据以进行快速测试,那就太好了

于 2017-09-15T07:31:07.800 回答
0
update st set cost = sl.cost from stock_table st
inner join sales_table sl on sl.Inventory_Code=st.Inventory_Code
and sl.Date = st.Date
于 2017-09-15T07:35:40.617 回答