SQL - 根据表中的条件查找特定日期

时间:2013-11-14 22:12:21

标签: sql oracle

我有2个表格,如下所示

EmployeeDetails - (employeeID,timestamp,status)
EmployeeActivity - (employeedID, timestamp, activity)

状态字段为0或1

我想要做的是,找到状态从1到0时的时间戳。使用此日期作为参数,查找表2中此日期之后完成的活动。

很抱歉,我目前无法提供示例查询。因为我不确定这是否可以使用单个查询完成,还是需要PL / SQL。

任何帮助将不胜感激。 感谢

修改

样本数据

表1

employeeID | timestamp | status
         1 | 01-NOV-13 |      1
         2 | 01-NOV-13 |      1
         1 | 02-NOV-13 |      0
         2 | 02-NOV-13 |      1
         1 | 03-NOV-13 |      0
         2 | 03-NOV-13 |      0

表2

employeeID | timestamp | activity
         1 | 01-NOV-13 |      1
         2 | 01-NOV-13 |      1
         1 | 02-NOV-13 |      0
         2 | 02-NOV-13 |      1
         1 | 03-NOV-13 |      1
         2 | 03-NOV-13 |      0

结果

employeeID | timestamp | activity
         1 | 03-NOV-13 |      1

这是输出,因为EmployeeId = 1在状态为0时有活动。

1 个答案:

答案 0 :(得分:2)

WITH previous_statuses AS (
  SELECT employeeID,
         timestamp_val,
         status,
         LAG( status ) OVER ( PARTITION BY employeeID ORDER BY timestamp_val ) AS previous_status
  FROM   employeeDetails
),
changed_statuses AS (
  SELECT employeeID,
         timestamp_val
  FROM   previous_statuses
  WHERE  status = 0
  AND    previous_status = 1
)
SELECT a.employeeID,
       a.timestamp_val,
       a.activity
FROM   employeeActivity a
       INNER JOIN
       changed_statuses s
       ON (    a.employeeID = s.employeeID
           AND a.timestamp_val = s.timestamp_val);

SQLFIDDLE