0

我有 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 时有活动。

4

1 回答 1

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

于 2013-11-14T22:57:31.213 回答