Sql server 2012 当field1=x1在某个日期时,在同一日期将field1=x2更改为x3
我有一张有时间信息的桌子。 工作日、雇员ID、日期类型、花费时间等 每个工作日将有多行。如果某个员工ID的任何工作日的TypeOfPay=x1,则将同一工作日和员工ID的所有TypeOfPay=x2更改为x3 原始数据Sql server 2012 当field1=x1在某个日期时,在同一日期将field1=x2更改为x3,sql-server-2012,Sql Server 2012,我有一张有时间信息的桌子。 工作日、雇员ID、日期类型、花费时间等 每个工作日将有多行。如果某个员工ID的任何工作日的TypeOfPay=x1,则将同一工作日和员工ID的所有TypeOfPay=x2更改为x3 原始数据 WorkDate EmployeeID TypeOfPay TimeSpent 2015-11-01 154 x1 8 2015-11-01 154 x2 2.5 2015-11-01
WorkDate EmployeeID TypeOfPay TimeSpent
2015-11-01 154 x1 8
2015-11-01 154 x2 2.5
2015-11-01 154 x2 1.1
2015-11-01 154 x4 1
2015-11-01 212 x1 8
2015-11-01 212 x4 4
2015-11-01 402 x2 7
结果
WorkDate EmployeeID TypeOfPay TimeSpent
2015-11-01 154 x1 8
2015-11-01 154 x3 2.5
2015-11-01 154 x3 1.1
2015-11-01 154 x4 1
2015-11-01 212 x1 8
2015-11-01 212 x4 4
2015-11-01 402 x2 7
提前谢谢
Gerry查询将如下所示。我假设表名为test1
update test1 a join test1 b on
a.workdate = b.workdate and a.employeeid=b.employeeid
set b.typeofpay = 'x3'
where a.typeofpay = 'x1' and b.typeofpay = 'x2'
这个查询在mysql上运行良好。sql server的查询几乎类似
对于SQL Server,以下查询将起作用
update b
set b.typeofpay = 'x3'
from test1 a join test1 b on
a.workdate = b.workdate and a.employeeid=b.employeeid
where a.typeofpay = 'x1' and b.typeofpay = 'x2'
我尝试了几件事,但都没有成功。这是让我困惑的标准,以及如何去做。对于每个员工ID和普通工作日,如果有x1和x2,则将x2更改为x3。我想过使用Case或self-join,但不知道从哪里开始。Msg 102,15级,状态1,第1行“a”附近语法不正确。感谢Gerry,上面的查询将在MySql上运行。对于Sql server,语法略有不同。请参阅SQL Server的已编辑答案。