SQL为员工添加小时数

时间:2015-05-12 13:05:13

标签: sql sql-server

我有一张供员工登记和退出的表格。它们具有输入和输出的日期和时间字段以及链接到员工姓名等的PersonID编号。

我需要弄清楚两个日期和时间之间的差异,然后为每个员工一起添加它们。

    select a.*,
           b.timein, 
           b.timeout, 
           datediff(mi,b.timein,b.timeout) as total_mins 
    from tbl_people a 
    left join tbl_register b on a.id=b.personid

输出:

+----+-----------+----------+-------------------------+-------------------------+------------+
| ID | FirstName | LastName |         TimeIn          |         TimeOut         | Total_Mins |
+----+-----------+----------+-------------------------+-------------------------+------------+
|  1 | David     | Test     | 2015-05-12 12:11:00.000 | 2015-05-12 12:13:00.000 |          2 |
|  2 | David     | Test     | 2015-05-12 12:15:00.000 | 2015-05-12 12:18:00.000 |          3 |
+----+-----------+----------+-------------------------+-------------------------+------------+

这就是我目前所获得的。我希望它能为每个人显示一个记录总分钟的记录。

感谢您的期待!

2 个答案:

答案 0 :(得分:0)

select
    ppl.FirstName + ' ' + ppl.LastName as 'Person',
    sum( datediff(mi, reg.timein, reg.timeout)) as 'total_mins'
from
    tbl_people ppl
    left join tbl_register reg on ppl.id = reg.personid
group by
    ppl.FirstName + ' ' + ppl.LastName

答案 1 :(得分:0)

基本上你至少有两个选择:

选项1 - 将DISTINCTSUMOVER条款一起使用:

SELECT DISTINCT a.*, 
       SUM(DATEDIFF(mi, b.timein, b.timeout)) OVER(PARTITION BY a.id) AS total_mins 
FROM tbl_people a 
LEFT JOIN tbl_register b ON a.id=b.personid

选项2 - derived table部分使用GROUP BY

SELECT a.*,
       total_mins            
from tbl_people a 
left join (
    SELECT personid, 
           SUM(DATEDIFF(mi, timein, timeout) AS total_mins 
    FROM tbl_register 
    GROUP BY personid 
 ) b ON a.id=b.personid