Select 顺序列记录,也找到最长的序列

Select sequential column records and also find the longest sequence

我希望针对不同的 ID 获得长度大于 1 的类型列的序列。

创建的table如下

 id | type 
----+------
  1 | E1
  1 | E1
  2 | A3
  3 | B2
  1 | A1
  4 | C1
  5 | C
  7 | D
  8 | D
  9 | A1
  3 | D
(11 rows)

这是我首先要实现的目标:

id | type
1  | E1
1  | E1
1  | A1
3  | B2
3  | D

上面的结果是我应该得到的序列类型 E1,E1,A1 for id 1 and B2,D for id 3.

我已经试过了,这无疑是错误的:

select q1.id, q1.type 
from 
    (select row_number() over () as rowno, * from recs) q1, 
    (select row_number() over () as rowno, * from recs) q2 
where q1.rowno > q2.rowno and  q1.id = q2.id;`

它给了我这样的东西:

 id | type 
----+------
  1 | E1
  1 | A1
  1 | A1
  3 | D
(4 rows)

在此之后我想找到最长的序列。

试试这个。 CTE 获取具有多个记录的 ID,查询仅提取这些记录。

WITH ids_recurring_more_than_once AS
(SELECT id FROM mytable GROUP BY id HAVING COUNT(*) >1)
SELECT m.* FROM mytable m
INNER JOIN ids_recurring_more_than_once 
ON m.id = ids_recurring_more_than_once.id

"longest sequence"是指重复次数最多的id吗?在这种情况下,将 CTE 替换为:

SELECT id FROM mytable GROUP BY id ORDER BY COUNT(*) DESC LIMIT 1

您可以使用 count() over partition:

select id, typ
from (
    select *, count(*) over (partition by id) seq_len
    from recs
    ) sub
where seq_len > 1

 id | typ
----+-----
  1 | A1
  1 | E1
  1 | E1
  3 | D
  3 | B2
(5 rows)    

或聚合序列:

select *
from (
    select id, array_agg(typ) seq
    from recs
    group by 1
    ) sub
where array_length(seq, 1) > 1

 id |    seq
----+------------
  1 | {E1,E1,A1}
  3 | {B2,D}
(2 rows)    

使用最后一个查询到select最长的序列:

select id, seq, array_length(seq, 1) seq_len
from (
    select id, array_agg(typ) seq
    from recs
    group by 1
    ) sub
order by 3 desc
limit 1

 id |    seq     | seq_len
----+------------+---------
  1 | {E1,E1,A1} |       3
(1 row)