如何加入同一个表的下一个日期值

时间:2014-09-18 02:09:03

标签: sql sql-server

我在SQL中有一个表,其中包含以下字段:

enter image description here

timestamp字段将包含员工一天内所有的一拳。

所以有以下数据:

enter image description here

我需要创建2个不同的查询。

  
      
  1. 需要选择所有IN时间戳及其对应的下一个OUT时间戳

  2.   
  3. 需要选择所有OUT时间戳及其对应的先前IN时间戳

  4.   

因此,在第一个查询中,我应该得到以下内容:

enter image description here

在第二个查询中,我应该得到以下内容:

enter image description here

  

有关如何构建此类查询的任何线索?

这里是小提琴http://sqlfiddle.com/#!6/a137d/1

2 个答案:

答案 0 :(得分:0)

这看起来是在SQL 2012中使用LEAD,LAG ANALYTIC函数的好例子。

SELECT * FROM
(
  SELECT EMPLOYEEID, TIMESTAMP,
  LEAD(timestamp) OVER (ORDER BY TIMESTAMP
  ) OUTTIMESTAMP, ACCESSCODE

  FROM [dbo].[employee_attendance]
  WHERE EMPLOYEEID =4 

) T 
where T.ACCESSCODE ='IN'

第二次查询

SELECT * FROM
(
  SELECT EMPLOYEEID, TIMESTAMP,
  LAG(timestamp) OVER (ORDER BY TIMESTAMP
  ) INTIMESTAMP, ACCESSCODE

  FROM [dbo].[employee_attendance]
  WHERE EMPLOYEEID =4 

) T 
where T.ACCESSCODE ='OUT'

答案 1 :(得分:0)

我相信这就是你要找的东西。这些查询应该适用于大多数DBMS。

第一

SELECT ea1.employeeid, ea1.timestamp AS instamp, ea2.timestamp AS outstamp
FROM employee_attendance ea1
LEFT JOIN employee_attendance ea2 
ON ea2.employeeid=ea1.employeeid 
AND ea2.accesscode = 'OUT' 
AND ea2.timestamp = (
    SELECT MIN(ea3.timestamp)
    FROM employee_attendance ea3
    WHERE ea3.timestamp > ea1.timestamp
    AND ea3.employeeid = ea1.employeeid
)
WHERE ea1.accessCode = 'IN'
AND ea1.employeeid = 4;

第二

SELECT ea1.employeeid, ea1.timestamp AS outstamp, ea2.timestamp AS instamp
FROM employee_attendance ea1
LEFT JOIN employee_attendance ea2 
ON ea2.employeeid=ea1.employeeid 
AND ea2.accesscode = 'IN' 
AND ea2.timestamp = (
    SELECT MIN(ea3.timestamp)
        FROM employee_attendance ea3
        WHERE ea3.timestamp < ea1.timestamp
        AND ea3.employeeid = ea1.employeeid
        AND ea3.timestamp > ISNULL((
            SELECT MAX(ea4.timestamp)
            FROM employee_attendance ea4
            WHERE ea4.accesscode = 'OUT'
            AND ea4.timestamp < ea1.timestamp
            AND ea4.employeeid = ea1.employeeid
        ), '2000-1-1')
)
WHERE ea1.accessCode = 'OUT'
AND ea1.employeeid = 4;