查找不同记录的时差

时间:2014-01-19 20:04:41

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

我有记录生物识别数据的数据库表,用于当USER ENTER /离开办公室时通过交换手指。

字段:

USERID EmpName, InOutTime, InOutDate 

现在当用户进入办公室时,它会记录

+------+-------+---------+---------+
|USERID|EmpName|InOutTime|InOutDate|
+------+-------+---------+---------+
|001   |John   |08:30    |12-12-13 | //When user enters office
+------+-------+---------+---------+
|001   |John   |04:30    |12-12-13 | //When user leaves office
+------+-------+---------+---------+

现在只有时间会改变,但我想从两个记录中找出时差(总工作时间),然后再显示它。

注意:意外的用户记录可以多次输入。

2 个答案:

答案 0 :(得分:3)

这是一个非常有用的查询,可以查看数据结构有多糟糕:

;WITH x AS 
(
  SELECT UserID, EmpName, InOutTime, InOutDate,
    rn = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY InOutDate, InOutTime)
  FROM dbo.tablename
)
SELECT *, DATEDIFF(MINUTE, x.InOutTime, y.InOutTime)
  FROM x LEFT OUTER JOIN x AS y
  ON x.UserID = y.UserID AND x.rn = y.rn -1;

在任何情况下,指纹在出路时都不会被扫描,这会产生各种疯狂的结果。这就是当你让非数据库人设计表时我得到的结果。 : - )

您确实需要重新访问该设计,以解决我在上述评论中概述的问题。

答案 1 :(得分:0)

您的数据

DECLARE @TABLE TABLE
 (USERID VARCHAR(10),EmpName VARCHAR(10),InOutTime TIME,InOutDate DATE)
 INSERT INTO @TABLE VALUES
('001','John','08:30','12-12-13'),('001','John','04:30','12-12-13'),
('002','Sam','05:30','12-12-13'),('002','Sam','04:30','12-12-13')

<强>查询

SELECT    t1.EmpName
        , t1.InOutTime AS InTime
        , t2.InOutTime AS [TimeOut]
        , t1.InOutDate AS [DateVisited]
        , DATEDIFF(HOUR,t1.InOutTime, t2.InOutTime) TotalHours
FROM  @TABLE t1 INNER JOIN @TABLE t2
ON    t1.USERID = t2.USERID 
AND   t1.InOutDate = t2.InOutDate
AND   t1.InOutTime < t2.InOutTime

结果集

╔═════════╦══════════════════╦══════════════════╦═════════════╦════════════╗
║ EmpName ║      InTime      ║     TimeOut      ║ DateVisited ║ TotalHours ║
╠═════════╬══════════════════╬══════════════════╬═════════════╬════════════╣
║ John    ║ 04:30:00.0000000 ║ 08:30:00.0000000 ║ 2013-12-12  ║          4 ║
║ Sam     ║ 04:30:00.0000000 ║ 05:30:00.0000000 ║ 2013-12-12  ║          1 ║
╚═════════╩══════════════════╩══════════════════╩═════════════╩════════════╝