Select最后一组连续行中的第一行

Select the first row in the last group of consecutive rows

我如何 select 连续行的最后 'grouping' 中第一次出现的行,其中分组由特定列值的连续出现定义(在示例中低于 state).

例如,给出以下 table:

id datetime state value_needed
1 2021-04-01 09:42:41.319000 incomplete A
2 2021-04-04 09:42:41.319000 done B
3 2021-04-05 09:42:41.319000 incomplete C
4 2021-04-05 10:42:41.319000 incomplete C
5 2021-04-07 09:42:41.319000 done D
6 2021-04-012 09:42:41.319000 done E

我想要带有 id=5 的行,因为它是 state=donestate=done.

的最后(即最近)分组中的第一次出现

假设所有列 NOT NULL

SELECT *
FROM   tbl t1
WHERE  NOT EXISTS (
   SELECT FROM tbl t2
   WHERE  t2.state <> t1.state
   AND    t2.datetime > t1.datetime
   )
ORDER  BY datetime
LIMIT  1;

db<>fiddle here

NOT EXISTS 仅适用于最后一组对等点。 (后面没有不同状态的行。) ORDER BY datetime 拿第一个。瞧。

这是一个 window 函数解决方案,它只访问您的 table 一次(对于大型数据集可能会或可能不会表现更好):

SELECT *
FROM (
  SELECT *, 
    LEAD (state) OVER (ORDER BY datetime DESC) 
      IS DISTINCT FROM state AS first_in_group
  FROM tbl
) t
WHERE first_in_group
ORDER BY datetime DESC
LIMIT 1

一个dbfiddle based on Erwin Brandstetter's。为了说明,这里是每行的 first_in_group 的值:

id  datetime                 state       value_needed  first_in_group
---------------------------------------------------------------------
6   2021-04-12 09:42:41.319  done        E             f
5   2021-04-07 09:42:41.319  done        D             t
4   2021-04-05 10:42:41.319  incomplete  C             f
3   2021-04-05 09:42:41.319  incomplete  C             t
2   2021-04-04 09:42:41.319  done        B             t
1   2021-04-01 09:42:41.319  incomplete  A             t