-2

我想计算员工在上午 9:00 到晚上 18:00 之间的总小时数。

我的数据库看起来像这样。

我怎样才能做到这一点??

AttendanceId     EmpId           CheckTime                  CheckType
-------------------------------------------------------------------------
   3               5             2013-01-03 09:00:15.000           1 (Login)
   4               5             2013-01-03 11:00:00.000           2 (Logout)
   5               5             2013-01-03 11:30:00.000           1 
   6               5             2013-01-03 13:00:00.000           2 
   7               5             2013-01-03 13:30:00.000           1 
   8               5             2013-01-03 16:00:00.000           2 
   9               5             2013-01-03 16:30:00.000           1 
  10               5             2013-01-03 18:00:00.000           2 
4

2 回答 2

2

由于您的Login/值在同一列中,因此首先登录/注销时间Logout可能更容易,然后再确定员工在场的总时间。PIVOTdatediff

查询的PIVOT部分是这样的:

select empid, [1], [2]
from
(
  select empid, checktime, checktype,
    row_number() over(partition by empid, checktype order by checktime) rn
  from yourtable
) src
pivot
(
  max(checktime)
  for checktype in ([1], [2])
) piv

请参阅带有演示的 SQL Fiddle

结果是:

| EMPID |                              1 |                              2 |
---------------------------------------------------------------------------
|     5 | January, 03 2013 09:00:15+0000 | January, 03 2013 11:00:00+0000 |
|     5 | January, 03 2013 11:30:00+0000 | January, 03 2013 13:00:00+0000 |
|     5 | January, 03 2013 13:30:00+0000 | January, 03 2013 16:00:00+0000 |
|     5 | January, 03 2013 16:30:00+0000 | January, 03 2013 18:00:00+0000 |

DateDiff()一旦数据处于这种结构中,您可以通过应用函数轻松获得时间差异。

生成员工登录时间的最终查询是:

select empid, sum(SecondsDiff) / 3600 as TotalHours
from
(
  select empid, datediff(ss, [1], [2]) SecondsDiff
  from
  (
    select empid, checktime, checktype,
      row_number() over(partition by empid, checktype order by checktime) rn
    from yourtable
  ) src
  pivot
  (
    max(checktime)
    for checktype in ([1], [2])
  ) piv
) src
group by empid

请参阅带有演示的 SQL Fiddle

结果是:

| EMPID | TOTALHOURS |
----------------------
|     5 |          7 |
于 2013-01-04T16:57:36.760 回答
0

要获得两个日期之间的差异,请使用以下DATEDIFF函数:http: //msdn.microsoft.com/en-us/library/ms189794.aspx

不过,我认为您需要逐行执行此操作。由于表的结构,您不能只进行简单的查询。

于 2013-01-04T16:17:51.823 回答