我想根据以下条件更新考勤表。比较上次日期和当前日期并根据条件更新表格
NonWorking
类型为1 如果它的前一天或下一个出勤类型不存在,则我想,以纪念NonWorking
类型LWP在DAOthers列。
我想根据以下条件更新考勤表。比较上次日期和当前日期并根据条件更新表格
NonWorking
类型为1 如果它的前一天或下一个出勤类型不存在,则我想,以纪念NonWorking
类型LWP在DAOthers列。
我认为你可以使用LAG()
和LEAD()
在这里出席类型的前面和值继续偷看。然后,如果其中一个不存在,请适当标记NonWorking
列。
WITH cte AS (
SELECT *,
LAG(AttendanceType, 1, 'Present') OVER (ORDER BY ADate) AS lag_at,
LEAD(AttendanceType, 1, 'Present') OVER (ORDER BY ADate) AS lead_at
FROM yourTable
)
UPDATE cte
SET NonWorking = 1
WHERE lag_at = 'Absent' OR lead_at = 'Absent'
它不是实际工作的错误转换数据类型为varchar为bigint它给错误。我认为它是因为这个LAG(AttendanceType,'Present')OVER(ORDER BY ADate)AS lag_at line –
你使用的是哪个版本的SQL Server? –
Sql Server 2012 –
我不确定您是否想要sql查询更新现有数据或进行输入时需要的解决方案。
Update AttendanceTable set DaOthers =
(select top 1 'LWP' from AttendanceTable at1
where AttendanceTable.EmployeeId = at1.EmployeeId
and DATEADD(day, -1,AttendanceTable.ADate) = at1.ADate
and at1.NonWorking = 1)
如果你想同时插入数据,那么你可能需要设置一个变量第一,然后使用该变量,同时插入更新。在第一个查询你需要使用A日期和EmployeeID.The非工作始终是1
DECLARE @DaOthers nvarchar(20) = (select top 1 'LWP' from AttendanceTable at
where DATEADD(day, 1, at.ADate) ='2017-02-04' and at.NonWorking = 1 and EmployeeId = 1)
insert into AttendanceTable
(NonWorking, ADate, AttendanceType, EmployeeId, DaOthers)
values
(0,'2017-02-04', 'Present', 1,@DaOthers)
With CTE as
(
SELECT *,
DATEADD(DAY, 1, Lag(ADate, 1,ADate)
OVER (PARTITION BY DAttendanceId ORDER BY ADate ASC)) AS EndDate
FROM tbl_DailyAttendance where EmployeeId = 1001 and AMonth = 2 and AYear = 2017 and AttendanceType = 'Absent' and NonWorking = 0
)
--select * from CTE
select * from tbl_DailyAttendance tda inner join CTE c on tda.ADate = c.EndDate where tda.EmployeeID = 1001 and tda.NonWorking = 1 order by tda.ADate
我这是怎么检查的条件
因为你hvn't提供的样本数据做的,所以请尝试理解我的查询并纠正是否有任何细微之处。
;WITH CTE as
(
select *
,isnull((select 1 from tbl_DailyAttendance tdb
where ((tdb.adate=DATEADD(day,-1,tda.adate))
or (tdb.adate=DATEADD(day,1,tda.adate)))
and attendancetype='Absent'
),0) NewnonWorkingType
from tbl_DailyAttendance tda
)
--Testing purpose
--select * from cte
update tda
set nonworking=b.NewnonWorkingType
,daOther=case when b.NewnonWorkingType=1 then 'LWP'
else null end
from tbl_DailyAttendance tda
inner join cte b on tda.id=b.id
...和你所期望的输出?尝试包括文字而不是图像。 –
我期待,如果2017年2月3日是缺席的话,我想,以纪念2017年2月4日的LWP在DAOthers列 –