初始表数据如下:
ID a b c
1 1 2 3
2 1 4 5
3 1 3 6
4 2 3 3
5 1 5 7
6 2 5 8
7 1 6 9
8 1 2 3
9 1 4 5
10 1 3 6
要求用SQL实现如下效果:
id a b c
1 1 2 3
2 1 4 5
3 1 3 6
7 1 6 9
8 1 2 3
9 1 4 5
10 1 3 6
SELECT min(ID)
FROM
(SELECT id,a,Row_number() OVER(partition by a order by id) AS Group_Index,
Row_number()OVER(ORDER BY id) AS Row_Index
FROM talbe) t
GROUP BY ( t. Group_Index - t.Row_Index)
HAVING count( t. Group_Index - t.Row_Index) =3
巧妙在于利于分组排序生成Id与自动生成排序ID的差,同在一个分组内,差值是相等的。