>假设您有两个事件表。 表 A 和 B 都有一列(称为时间戳(,其中包含多行。
现在,我想将这两个表合并到具有以下属性的表 C 中:
- C 对 A 中的每一行都有一行
- C 有一个时间戳列,完美地反映了 A 的内容
- C 有另一列称为 near_event如果 B 中在该行时间戳的 1 秒内有一行,则为 true,否则为 false。
我怎样才能有效地做到这一点?
Mauro 向我指出了这一点,说 Vertica 可以做得更好 - 事实上,它可以,因为它有一个谓词,可以实现我们所说的事件系列加入。您需要做的就是运行非内部连接(左、右或完全外部(,并智能地使用 INTERPOLATE PREVIOUS VALUE
作为连接谓词。
你可能想看看我的LinkedIn帖子:
https://www.linkedin.com/pulse/verticas-event-series-join-joining-two-time-tables-marco-gessner/
..这说明了一个更复杂的用例。
使用与该博客中相同的表:
CREATE LOCAL TEMPORARY TABLE oilpressure (
op_ts,op_psi
) ON COMMIT PRESERVE ROWS AS (
SELECT TIMESTAMP '2015-04-01 07:00:00', 25.356
UNION ALL SELECT TIMESTAMP '2015-04-01 07:00:10', 35.124
UNION ALL SELECT TIMESTAMP '2015-04-01 07:00:20', 47.056
UNION ALL SELECT TIMESTAMP '2015-04-01 07:00:30', 45.225
)
;
CREATE LOCAL TEMPORARY TABLE revspeed (
rs_ts,rpm
) ON COMMIT PRESERVE ROWS AS (
SELECT TIMESTAMP '2015-04-01 07:00:00', 2201
UNION ALL SELECT TIMESTAMP '2015-04-01 07:00:08', 3508
UNION ALL SELECT TIMESTAMP '2015-04-01 07:00:15', 6504
UNION ALL SELECT TIMESTAMP '2015-04-01 07:00:20', 6608
)
;
让oilpressure
成为您的 A 桌,revspeed
成为您的 B 桌。
那么你想要的(如果你只想要时间戳(是这样的:
SELECT
op_ts
, rs_ts
FROM oilpressure
LEFT JOIN revspeed
ON op_ts INTERPOLATE PREVIOUS VALUE rs_ts;
op_ts |rs_ts
2015-04-01 07:00:00|2015-04-01 07:00:00
2015-04-01 07:00:10|2015-04-01 07:00:08
2015-04-01 07:00:20|2015-04-01 07:00:20
2015-04-01 07:00:30|2015-04-01 07:00:20
如果您没有太多重复项,则可以执行此操作。 这是这个想法:
select timestamp,
(case when timestamp < timestamp_add(second, 1, last_b_timestamp) or
timestamp > timestamp_add(second, -1, next_b_timestamp)
then 1 else 0
end) as flag
from (select timestamp, which,
last_value(case when which = 'b' then timestamp) over (order by timestamp) as last_b_timestamp,
last_value(case when which = 'b' then timestamp) over (order by timestamp desc) as next_b_timestamp,
from ((select a.timestamp, 'a' as which from a) union all
(select b.timestamp, 'b' as which from b)
) ab
) ab
where which = 'a';