我正在尝试找出员工时钟的日期和结束日期。以下是我拥有的数据的示例。
PersonID EventTime ActivityCode
1 2019-07-29 00:03:03.000 7
1 2019-07-29 00:09:41.000 0
1 2019-07-29 00:01:07.000 7
1 2019-07-29 00:01:19.000 0
想要的输出:
PersonID EventTime EndTime ActivityCode
1 2019-07-29 00:03:03.000 2019-07-29 00:09:41.000 7
1 2019-07-29 00:09:41.000 2019-07-29 00:01:07.000 0
1 2019-07-29 00:01:07.000 2019-07-29 00:01:19.000 7
1 2019-07-29 00:01:19.000 0
我必须根据事件时间和活动代码找到此人的开始日期和结束日期。开始日期将是事件时间列,我必须从同一列(即该行中的下一个事件时间)计算结束日期。
我已经尝试过在T-SQL中使用Lead函数,但是它没有给我想要的结果。
select personid, activitycode, eventtime as starttime
, (lead(eventtime) over (order by personid)) as endtime
from ActivityTable
[如果有人对如何解决这个问题有所了解,我将不胜感激。
您的输出在您的示例中看起来很奇怪,因为EventTime似乎在EndTime之后发生。如果您正在寻找时间顺序,并且期望这样的结果集:
然后xQbert的评论是正确的。您只需要在Order By中添加EventTime。请参见下面的示例代码。
CREATE TABLE #T (
PersonID INT
,EventTime DATETIME
,ActivityCode INT
)
INSERT INTO #T(
PersonID
,EventTime
,ActivityCode
)
SELECT
PersonID
,EventTime
,ActivityCode
FROM
(VALUES ( 1,'2019-07-29 00:03:03.000', 7)
,(1,'2019-07-29 00:09:41.000', 0)
,(1,'2019-07-29 00:01:07.000', 7)
,(1,'2019-07-29 00:01:19.000', 0)) AS T (PersonID,EventTime,ActivityCode)
SELECT
PersonID
,ActivityCode
,EventTime AS starttime
,(LEAD(EventTime) OVER (ORDER BY PersonID, EventTime DESC)) AS endtime
FROM
#T;
我怀疑您的EventTime应该是13:00而不是01:00
示例
Declare @YourTable Table ([PersonID] varchar(50),[EventTime] datetime,[ActivityCode] int) Insert Into @YourTable Values
(1,'2019-07-29 00:03:03.000',7)
,(1,'2019-07-29 00:09:41.000',0)
,(1,'2019-07-29 00:13:07.000',7) << changed to 13
,(1,'2019-07-29 00:13:19.000',0) << changed to 13
Select PersonID
,EventTime
,EndTime= lead([EventTime],1) over (partition by [PersonID] order by [EventTime])
,ActivityCode
From @YourTable
Order by EventTime
返回
PersonID EventTime EndTime ActivityCode
1 2019-07-29 00:03:03.000 2019-07-29 00:09:41.000 7
1 2019-07-29 00:09:41.000 2019-07-29 00:13:07.000 0
1 2019-07-29 00:13:07.000 2019-07-29 00:13:19.000 7
1 2019-07-29 00:13:19.000 NULL 0