Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. WITH Level1
  2. AS (-- apply row numbers
  3. SELECT emp_reader_id ,
  4.  
  5. CAST(dt AS DATETIME) AS [DATETIME] ,
  6. ROW_NUMBER() OVER ( PARTITION BY emp_reader_id
  7. ORDER BY dt ) AS RowNum
  8. FROM trnevents
  9. ),
  10. LEVEL2
  11. AS (-- find the last and next event type for each row
  12. SELECT A.emp_reader_id ,
  13. A.DATETIME ,
  14. COALESCE(NULL, 'N/A') AS LastEvent ,
  15. COALESCE(NULL, 'N/A') AS NextEvent
  16. FROM Level1 A
  17. LEFT JOIN Level1 LastVal
  18. ON A.emp_reader_id = LastVal.emp_reader_id
  19. AND A.RowNum - 1 = LastVal.RowNum
  20. LEFT JOIN Level1 NextVal
  21. ON A.emp_reader_id = NextVal.emp_reader_id
  22. AND A.RowNum + 1 = NextVal.RowNum ),
  23. Level3
  24. AS (-- reapply row numbers to row-eliminated set
  25. SELECT emp_reader_id ,
  26.  
  27. DATETIME ,
  28. LastEvent ,
  29. NextEvent ,
  30. ROW_NUMBER() OVER ( PARTITION BY emp_reader_id
  31. ORDER BY DATETIME ) AS RowNBr
  32. FROM Level2
  33. ),
  34. Level4
  35. AS (-- pair enter and exit rows.
  36. SELECT A.emp_reader_id ,
  37. A.DATETIME ,
  38. B.DATETIME AS ExitDATETIME
  39. FROM Level3 A
  40. JOIN Level3 B ON A.emp_reader_id = B.emp_reader_id
  41. AND A.RowNBr + 1 = B.RowNBr
  42. ),
  43. LEVEL5
  44. AS (--Calculate the work session duration
  45. SELECT emp_reader_id ,
  46.  
  47. DATEDIFF(second, DATETIME, ExitDATETIME)
  48. AS Seconds ,
  49. DATETIME ,
  50. ExitDATETIME
  51. FROM Level4
  52. )
  53.  
  54. SELECT emp_reader_id ,
  55.  
  56. CAST([DATETIME] AS date) AS [dt],
  57. CAST([DATETIME] AS Time) as [In],
  58. CAST(ExitDATETIME AS Time) As Out,
  59. RIGHT('0' + CAST(Seconds / 3600 AS VARCHAR(2)), 2) + ':'
  60. + RIGHT('0' + CAST(Seconds % 3600 / 60 AS VARCHAR(2)), 2) + ':'
  61. + RIGHT('0' + CAST(Seconds % 3600 % 60 AS VARCHAR(2)), 2)
  62. AS TotalHours
  63. FROM Level5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement