我在下面列出一个例子。我有带有Seq编号的Id列,我需要按ID对它们进行分组,以及Seq编号不按顺序的地方。 顺便说一下,我正在使用Teradata。
数据:
DATA Sample
id Seq
abcd 1
abcd 2
abcd 3
abcd 5
abcd 6
abcd 7
abcd 8
abcd 10
abcd 11
ab 2
ab 3
ab 4
ab 8
ab 9
预期结果
id Seq Group_nbr
abcd 1 1
abcd 2 1
abcd 3 1
abcd 5 2
abcd 6 2
abcd 7 2
abcd 8 2
abcd 10 3
abcd 11 3
ab 2 1
ab 3 1
ab 4 1
ab 8 2
ab 9 2
答案 0 :(得分:2)
您需要应用嵌套的OLAP函数:
SELECT id, Seq,
Sum(Flag) -- assign a group number
Over (PARTITION BY id
ORDER BY Seq
ROWS Unbounded Preceding) AS group_nbr
FROM
(
SELECT id, Seq,
CASE WHEN Max(Seq) -- indicate if there's a gap in the sequence
Over (PARTITION BY id
ORDER BY Seq
ROWS BETWEEN 1 Preceding AND 1 Preceding) + 1 = Seq
THEN 0
ELSE 1
END AS flag
FROM tab
) AS dt