以下是我表格中的模型数据。
Data:
Date Worked Hours IsLate
8/1/2013 8:03:00 No
8/2/2013 10:52:00 No
8/3/2013 8:43:00 Yes
8/4/2013 9:26:00 No
如果前一天工作时间等于10小时,则IsLate列将更新为“是”。如何计算前一行值是否等于10小时。
请帮帮我。
答案 0 :(得分:3)
查询:
<强> SQLFIDDLEExample 强>
with table5
as (
SELECT Date,
[Worked Hours],
IsLate,
ROW_NUMBER() OVER (ORDER BY Date ASC, [Worked Hours] ASC) AS RowNumber1
FROM Table1
)
SELECT t1.Date,
t1.[Worked Hours],
t1.IsLate,
CASE WHEN LEFT(t2.[Worked Hours],2) = '10'
THEN 'Equal'
ELSE 'Not Equal' END AS isequal
FROM table5 t1
LEFT JOIN table5 t2
ON t1.RowNumber1 - 1 = t2.RowNumber1
结果:
| DATE | WORKED HOURS | ISLATE | ISEQUAL |
|-------------------------------|--------------|--------|-----------|
| August, 01 2013 00:00:00+0000 | 8:03:00 | No | Not Equal |
| August, 02 2013 00:00:00+0000 | 10:52:00 | No | Not Equal |
| August, 03 2013 00:00:00+0000 | 8:43:00 | Yes | Equal |
| August, 04 2013 00:00:00+0000 | 9:26:00 | No | Not Equal |
如果您只想更新表格,请使用:
<强> SQLFIDDLEExample 强>
UPDATE Table1
SET [IsLate] = ISNULL((SELECT TOP 1 CASE WHEN LEFT(t1.[Worked Hours],2) = '10'
THEN 'Equal'
ELSE 'Not' END
FROM Table1 t1
WHERE t1.Date < Table1.Date
ORDER BY t1.Date DESC), 'Not')
结果:
| DATE | WORKED HOURS | ISLATE |
|-------------------------------|--------------|--------|
| August, 01 2013 00:00:00+0000 | 8:03:00 | Not |
| August, 02 2013 00:00:00+0000 | 10:52:00 | Not |
| August, 03 2013 00:00:00+0000 | 8:43:00 | Equal |
| August, 04 2013 00:00:00+0000 | 9:26:00 | Not |
答案 1 :(得分:0)
IF 10 <= (SELECT DATEPART(hh, Worked_Hours) from Data)
Begin
Update Data set isLate = 'No'
where ..
End
答案 2 :(得分:0)
update yourtable
set late='yes'
from yourtable
where
(select top 1 datepart(hh,worked)
from yourtable t2
where t2.workdate<yourtable.workdate order by workdate desc)=10
答案 3 :(得分:0)
这个怎么样?
declare @d table (WorkedDate date,WorkedHours time,IsLate varchar(10));
insert @d select '8/1/2013','8:03',null;
insert @d select '8/2/2013','10:52',null;
insert @d select '8/3/2013','8:43',null;
insert @d select '8/4/2013','9:26',null;
update @d set IsLate=case when exists (select WorkedHours from @d p where p.WorkedDate=dateadd(day,-1,d.WorkedDate) and WorkedHours>'10:00') then 'Yes' else 'No' end
from @d d;
select * from @d;