满足2个条件时更改字段

时间:2016-09-12 21:05:14

标签: sql-server-2012

我有一个时间表数据库,需要在以下示例中更改TypeOfPay

如果某人获得Stat Holiday(TypeOfPay = Stat Holiday)的付款并且当天工作(TypeOfPay =常规),请将所有行更改为TypeOfPay = Stat In。

  1. 日期说明员工TypeOfPay TimeSpent
  2. 2016-09-05 ABC_Company BobJones Stat Holiday 8.00
  3. 2016-09-05 BCD_Company BobJones常规1.25
  4. 2016-09-05 Lift_Check BobJones常规0.25
  5. 提前致谢 格里

1 个答案:

答案 0 :(得分:1)

这是一个非常简单的更新。您使用您提供的条件(相同日期,假期与常规和同一员工)将表连接到自身并更新薪酬类型。 您可以通过仅在没有更新的情况下进行连接来查看关联。

select * 
from #Timesheet t
left join #Timesheet holiday on t.date = holiday.date and t.employee = holiday.employee and t.typeofPay = 'regular' and holiday.typeofpay = 'Stat Holiday'

这是我使用的表格设置。显然你会用你的实际表名

替换#Timesheet
create table #Timesheet
(
[Date] Date not null,
[Description] varchar(20) null,
[Employee] varchar(30) not null,
[TypeOfPay] varchar(12) null,
[TimeSpent] Numeric (12,2) null
)
Insert into #Timesheet 
(Date,Description, Employee, TypeOfPay, TimeSpent)
Values
('2016-09-05', 'ABC_Company', 'BobJones', 'Stat Holiday', 8.00),
('2016-09-05', 'BCD_Company', 'BobJones', 'regular' ,1.25),
('2016-09-05', 'Lift_Check', 'BobJones', 'regular', 0.25),
('2016-09-05', 'ABC_Company', 'BobJones', 'Stat Holiday', 8.00), 
('2016-09-05', 'BCD_Company', 'BobJones', 'regular' ,1.25), 
('2016-09-05', 'Lift_Check', 'BobJones', 'regular', 0.25), 
('2016-09-05', 'Lift_Check', 'JoeSmith', 'regular', 0.25), 
('2016-09-06', 'Lift_Check', 'BobJones', 'regular', 0.25)

  update t --(this is your timesheet table)
Set t.TypeOfPay = 'Stat in' 
from #Timesheet t
inner join #Timesheet holiday on t.date = holiday.date and t.employee = holiday.employee and t.typeofPay = 'regular' and holiday.typeofpay = 'Stat Holiday'
where t.TypeOfPay <> 'Stat Holiday'  

您可以通过查看更新的表进行验证。

select * from #Timesheet