总工时

时间:2013-07-03 15:20:18

标签: sql sql-server sql-server-2008

log_date    log_time           emp_id    emp_name          log_action       
2013-06-16  08:48:48.0000000    30170   Sarah John          1
2013-06-16  16:48:48.0000000    30170   Sarah John          4
2013-06-15  07:18:48.0000000    30160   Paula Fred          1
2013-06-15  16:38:48.0000000    30160   Paula Fred          4

我有一个包含上述信息的日志表。我有一个查询来计算每个员工的日常工作时间,并将它们存储在另一个员工的十进制字段中。问题是会议记录关闭,如果员工在同一天多次打卡/打卡,则会增加小时数。我希望它只能说明第一个好的打孔/打孔。

Select DISTINCT emp_id,log_date,SUM(datediff(Minute,stm, etm))/60.0
  as wrk_hrs from
(
    SELECT
        emp_id, log_date,
        log_time as etm,
        (
            SELECT top 1 log_time
            FROM tblLogs
            WHERE log_action = '1' and log_time <= a.log_time and emp_id=a.emp_id and a.log_date=log_date order by log_time desc
        ) as stm
    FROM tblLogs as a
    WHERE log_action = '4'
)as a
where stm is not null
group by log_date,emp_id,a.stm,a.etm;

是否有更准确的方法来计算小时和分钟并将其存储以供进一步计算。我需要一段时间和每周总时间来报告。

3 个答案:

答案 0 :(得分:0)

由于您只需要每个员工日活动的第一个条目:

SELECT
  [log_date],
  [emp_id],
  [emp_name],
  [1] AS [first_log_in],
  [4] AS [first_log_out],
  DATEDIFF(minute,[1],[4])/60.0 AS [hours]
FROM @tblLogs
PIVOT(MIN(log_time) FOR log_action IN ([1],[4])) p

这假设您的日志数据状况良好。如果您需要在打孔前检查打孔前打孔或多打孔,这是一个完全不同的问题。

答案 1 :(得分:0)

SELECT StartLog.emp_id, StartLog.log_date,  SUM(datediff(Minute,stm, etm))/60.0
FROM (
    SELECT emp_id, log_date, MIN(log_time) AS stm 
    FROM tblLogs
    WHERE log_action = '1'
    GROUP BY emp_id, log_date
    ) AS StartLog
INNER JOIN 
    (
        SELECT emp_id, log_date, MIN(log_time) AS etm 
        FROM tblLogs
        WHERE log_action = '4'
        GROUP BY emp_id, log_date
    ) AS EndLog
    ON StartLog.emp_id = EndLog.emp_id AND StartLog.log_date = EndLog.log_date

答案 2 :(得分:0)

如果您想要更高的准确度,请切换到秒:

Select emp_id,log_date,SUM(datediff(second,stm, etm))/3600.0
  as wrk_hrs from
(
    SELECT
        emp_id, log_date,
        log_time as etm,
        (
            SELECT top 1 log_time
            FROM tblLogs
            WHERE log_action = '1' and log_time <= a.log_time and emp_id=a.emp_id and a.log_date=log_date order by log_time desc
        ) as stm
    FROM tblLogs as a
    WHERE log_action = '4'
)as a
where stm is not null
group by log_date,emp_id,a.stm,a.etm;

注意:使用distinct时,group by通常完全是多余的。