Splitting time column into start time / end time columns

让人想犯罪 __ 提交于 2019-12-10 23:24:17

问题


I have a table that contains information regarding what they've done throughout the day. I need to get the start time/end time for each task.

Currently I am able to pull the timestamp of each task, but I am hoping to create Start Times and End Times columns. Start time would be the timestamp from the previous row, and end time would be the timestamp from the current row.

Is there any simple way to do this? Here is the query that I am currently using.

select  
Timestamp,
Sku,
Station,
Username,
ActionType
from OverallLogs


where 
and ActionType = 'Put'
and Username = 'Name'
and timestamp < DateAdd(Day, DateDiff(Day, 0, GetDate())+1, 0)
AND timestamp >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)

Order by timestamp desc

回答1:


you might want to use sql cte option, look for some help on the link, SQL Find difference between previous and current row

My suggestion would be keep single record for activity, if your first record is start and next is end of that task.

If you do not want to change schema, then may add one more column depicting the task type column that it was a start or end. It will help you in future in queries.




回答2:


If you want to get the value of last line ,you can use LAG function. Example

;WITH sampledata(ID, t) AS(
  SELECT 1 ,DATEADD(HOUR,-12,GETDATE()) UNION
  SELECT 2 ,DATEADD(HOUR,-8,GETDATE()) UNION
  SELECT 3 ,DATEADD(HOUR,-4,GETDATE()) UNION
  SELECT 4 ,DATEADD(HOUR,-2,GETDATE()) UNION
  SELECT 5 ,DATEADD(HOUR,-1,GETDATE()) 

)
SELECT *,LAG(t)OVER(ORDER BY t ) AS start_t FROM sampledata
ID          t                       start_t
----------- ----------------------- -----------------------
1           2017-06-03 06:48:59.447 NULL
2           2017-06-03 10:48:59.447 2017-06-03 06:48:59.447
3           2017-06-03 14:48:59.447 2017-06-03 10:48:59.447
4           2017-06-03 16:48:59.447 2017-06-03 14:48:59.447
5           2017-06-03 17:48:59.447 2017-06-03 16:48:59.447


来源:https://stackoverflow.com/questions/44347592/splitting-time-column-into-start-time-end-time-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!