Vertica / SQL:立即获取行继续执行事件

时间:2018-05-09 15:18:42

标签: sql vertica

考虑一个简单的查询

select from tbl where status=MELTDOWN

我现在想创建一个表,除了包含这些行之外,还包括前面的p行和后续的n行,这样我就可以了解这些MELTDOWN周围时间发生的情况。任何提示?

2 个答案:

答案 0 :(得分:1)

你可以通过获取熔化行的seqnum来实现窗口函数。我更喜欢使用lag()/lead() ignore nulls执行此操作,但Vertical不支持此功能。我认为这等同于first_value()/last_value()

with t as (
      select t.*, row_number() over (order by id) as seqnum
      from tbl
     ),
     tt as (
      select t.*,
             last_value(case when status = 'meltdown' then seqnum end ignore nulls) over (order by seqnum rows between unbounded preceding and current row) as prev_meltdown_seqnum,
             first_value(case when status = 'meltdown' then seqnum end ignore nulls) over (order by seqnum rows between current row and unbounded following) as prev_meltdown_seqnum,
      from t
     )
select tt.*
from tt
where seqnum between prev_melt_seqnum and prev_melt_seqnum + 7 or
      seqnum between next_melt_seqnum -5 and next_melt_seqnum;

答案 1 :(得分:0)

WITH
  grouped AS
(
  SELECT
    SUM(
      CASE WHEN status = 'Meltdown' THEN 1 ELSE 0 END
    )
    OVER (
      ORDER BY timeStamp
    )
      AS GroupID,
    tbl.*
  FROM
    tbl
),
  sorted AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY GroupID ORDER BY timeStamp ASC )   AS incPos,
    ROW_NUMBER() OVER (PARTITION BY GroupID ORDER BY timeStamp DESC)   AS decPos,
    MAX(GroupID) OVER ()                                               AS LastGroup
    grouped.*
  FROM
    grouped
)
SELECT
  sorted.*
FROM
  sorted
WHERE
     (incPos <= 8 AND GroupID  > 0        )   -- Meltdown and the 7 events following it
  OR (decPos <= 6 AND GroupID <> LastGroup)   --          and the 6 events preceding a Meltdown
ORDER BY
  timeStamp