2017-02-27 50 views
1

我想根據以下條件更新考勤表。比較上次日期和當前日期並根據條件更新表格

NonWorking類型爲1 如果它的前一天或下一個出勤類型不存在,則我想,以紀念NonWorking類型LWP在DAOthers列。

enter image description here

+2

...和你所期望的輸出?嘗試包括文字而不是圖像。 –

+0

我期待,如果2017年2月3日是缺席的話,我想,以紀念2017年2月4日的LWP在DAOthers列 –

回答

0

我認爲你可以使用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' 
+0

它不是實際工作的錯誤轉換數據類型爲varchar爲bigint它給錯誤。我認爲它是因爲這個LAG(AttendanceType,'Present')OVER(ORDER BY ADate)AS lag_at line –

+0

你使用的是哪個版本的SQL Server? –

+0

Sql Server 2012 –

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) 

表befor上述查詢執行:

enter image description here

到:

enter image description here

表上面的查詢執行後在插入記錄的更新時間:

如果你想同時插入數據,那麼你可能需要設置一個變量第一,然後使用該變量,同時插入更新。在第一個查詢你需要使用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) 
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 

我這是怎麼檢查的條件

0

因爲你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 
相關問題