0

我什至不知道如何问这个问题,但我会举例说明我想要实现的目标。

 ID  NAME   ACTIVITY  TIMESTAMP
 1    ..      book      timestamp
 1    ..      eat       timestamp
 1    ..      sleep     timestamp

 2    ..      apple     timestamp
 2    ..      eat       timestamp
 2    ..      sleep     timestamp
 2    ..      book      timestamp

 3    ..      eat       timestamp
 3    ..      sleep     timestamp
 3    ..      book      timestamp
 3    ..      sleep     timestamp

 4    ..      eat       timestamp1
 4    ..      sleep     timestamp1
 4    ..      sleep     timestamp2
 4    ..      eat       timestamp2

只有当下一条记录eatsleep并且它们都具有相同timestampID

所以输出会。对于此示例,它们都具有相同的时间戳。when ID=4它发生了两次,但它有不同的timestamp.

 ID  NAME   ACTIVITY  TIMESTAMP

 1    ..      eat        timestamp
 1    ..      sleep      timestamp

 2    ..      eat        timestamp
 2    ..      sleep      timestamp

 3    ..      eat        timestamp
 3    ..      sleep      timestamp

 4    ..      eat        timestamp1
 4    ..      sleep      timestamp1
 4    ..      sleep      timestamp2
 4    ..      eat        timestamp2
4

1 回答 1

2

分析LAGLEAD函数可以解决问题:

SELECT ID, Name, Activity, Timestamp
FROM (
  SELECT
    ID,
    Name,
    Activity,
    Timestamp,
    LAG(Activity) OVER (PARTITION BY ID, Timestamp ORDER BY Activity) AS PriorActivity,
    LEAD(Activity) OVER (PARTITION BY ID, Timestamp ORDER BY Activity) AS NextActivity
  FROM Activity
  WHERE Activity IN ('eat', 'sleep')
)
WHERE (Activity = 'eat' and NextActivity = 'sleep')
   OR (Activity = 'sleep' AND PriorActivity = 'eat')

内部查询排除了任何不是eator的活动sleep,它捕获了 and 的前一个 ( LAG) 和下一个 ( LEAD) 活动IDTimestamp按活动名称排序 - 这恰好适合,因为eat排序 before sleep

外部查询只是确保eat后面是sleep并且sleep前面是eat. ID由于内部查询的分区,只有在相同的和下找到两种类型时才会出现这种情况Timestamp

如果您对查询有任何疑问,请尝试自行运行内部查询 - 这将显示由外部查询过滤的原始数据。

于 2013-05-22T15:03:57.703 回答