比较上一个日期和当前日期,并根据条件更新表格

时间:2017-02-27 04:42:48

标签: sql-server

我想根据以下条件更新我的出勤表。

NonWorking类型为1 如果其前一天或下一个出勤类型不存在,那么我想在DAOthers列中标记NonWorking类型为LWP。

enter image description here

4 个答案:

答案 0 :(得分:0)

我认为您可以在此处使用col-xs-12LAG()来查看出勤类型的前一个和前一个值。然后,如果其中一个不存在,请正确标记LEAD()列。

NonWorking

答案 1 :(得分:0)

我不确定您是否需要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)

表执行上述查询:

enter image description here

执行上述查询后的表:

enter image description here

在插入记录时更新:

如果要在插入数据时更新,则可能需要先设置变量,然后在插入时使用该变量。在第一个查询中,您需要使用ADate和EmployeeID。非工作始终为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)

答案 2 :(得分:0)

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

这是我检查条件的方法

答案 3 :(得分:0)

因为您没有提供样本数据,所以请尝试理解我的查询并纠正是否有任何小问题。

;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