将旧店改为新店

时间:2017-11-14 05:28:35

标签: database sql-server-2008

我想通过在MSSQL中使用查询将旧存储更改为新存储。例如,

Staff_Id名称Transaction_Date New_Store Old_Store

1 AA 1.1.2017 1

1 AA 1.2.2017 2

1 AA 1.3.2017 3

1 AA 1.4.2017 1

1 AA 1.5.2017 4

我想将表更改为以下

Staff_Id名称Transaction_Date New_Store Old_Store

1 AA 1.1.2017 1 NULL

1 AA 1.2.2017 2 1

1 AA 1.3.2017 3 2

1 AA 1.4.2017 1 3

1 AA 1.5.2017 4 1

我写了这样的查询,但事实并非如此,它随机输出更新EC1 SET EC1.Old_Store = EC.New_Store  从Employee_Change EC,Employee_Change EC1 在哪里EC.Staff_Id = EC1.Staff_Id AND EC.Transaction_Date> = EC1.Transaction_Date

1 个答案:

答案 0 :(得分:0)

UPDATE EC SET Old_Store =(SELECT TOP 1 New_Store FROM Employee_Change As EC1 WHERE EC1.Staff_Id = EC.Staff_Id和EC1.Transaction_Date< EC.Transaction_Date ORDER BY EC1.Transaction_Date DESC)FROM Employee_Change As EC