如何使用sql获取员工的所有intime和outtime?

时间:2017-12-09 05:47:06

标签: sql sql-server

鉴于表:

id       time_stamp                  Access Type    
0301    2013-09-05 09:35:00         0
0302    2013-09-05 11:00:00         0
0301    2013-09-05 12:00:00         1
0302    2013-09-05 12:25:00          1
0301    2013-09-05 13:00:00          0
0302    2013-09-05 14:00:00         0
0301    2013-09-05 17:00:00          1
0302    2013-09-05 18:00:00         1

从上面的表中我想为每个员工显示Intime和Outtime ... 0 in in和1 in out。

预期产出:

id      check_in    check_out duration check_in    check_out duration  date           Totalduration
0301    09:35       12:00      02:25   13:00       17:00      04:00   2013-09-05          08:00
0302    11:00       12:25      01:25   14:00       18:00      04:00    2013-09-05          07:00

结果会像这样继续......

1 个答案:

答案 0 :(得分:0)

我会考虑一下。乍一看:

SELECT t1.id,
       t1.time_stamp AS check_in,
       COALESCE((SELECT min(t2.time_stamp)
                   FROM t t2
                  WHERE t1.id = t2.id
                    AND t1.time_stamp < t2.time_stamp
                    AND t2.access_type = 1), NULL) AS check_out
  INTO TEMPORARY TABLE tt
  FROM t t1
 WHERE t1.access_type = 0;

  SELECT id,
         check_in,
         check_out, 
         CASE WHEN check_out IS NOT NULL
              THEN EXTRACT('epoch' FROM check_out) - EXTRACT('epoch' FROM check_in)
              ELSE 0
              END AS duration
    FROM tt
ORDER BY id, check_in;

DROP TEMPORARY TABLE tt;

我不知道该纪元代码或临时表语法是否适用于您的特定数据库,您可能需要调整该部分。