※欠損の基準は、整数値を0から順に並べたときに欠けている整数のことを指します
配列長は現状最大30個までですが、これから先その最大長が更新される可能性があるため、
可変長であることを仮定したプログラム
以下でどうでしょう。
※ データサンプルは FROM...VALUES...( a, b ) の箇所です
SQL
1SELECT a _group
2 , b _aggregate
3 , coalesce( min( case when d - c != 1 then e end )
4 , max(c)
5 ) _result
6FROM
7(
8 SELECT a, b, c, d
9 , lag( c, 1, 0 ) over ( partition by a order by c ) e
10 FROM
11 (
12 VALUES
13 ( 1, array[0,1,2,4,5]::int[] )
14 , ( 2, array[0,1,2,3]::int[] )
15 , ( 3, array[0,1,5]::int[] )
16 , ( 4, array[0,1]::int[] )
17 , ( 5, array[0,1,2,5]::int[] )
18 , ( 6, array[1,2,3]::int[] )
19 ) t1 ( a, b )
20 , LATERAL unnest( b ) with ordinality t2 ( c, d )
21) q
22GROUP BY a, b
23ORDER BY 1
24;
■ 結果
_group | _aggregate | _result |
---|
1 | {0,1,2,4,5} | 2 |
2 | {0,1,2,3} | 3 |
3 | {0,1,5} | 1 |
4 | {0,1} | 1 |
5 | {0,1,2,5} | 2 |
6 | {1,2,3} | 0 |
以下はコメントいただいたロジックや回答とは別の記述方法:
SQL
1SELECT a _group
2 , b _aggregate
3 , (
4 SELECT coalesce(
5 min( coalesce( b[ d - 1 ], 0 ) ) filter( where d - c != 1 )
6 , max( c )
7 )
8 FROM unnest( b )
9 with ordinality t ( c, d )
10 ) _result
11FROM
12(
13 VALUES
14 ( 1, array[0,1,2,4,5]::int[] )
15 , ( 2, array[0,1,2,3]::int[] )
16 , ( 3, array[0,1,5]::int[] )
17 , ( 4, array[0,1]::int[] )
18 , ( 5, array[0,1,2,5]::int[] )
19 , ( 6, array[1,2,3]::int[] )
20) q ( a, b )
21ORDER BY 1
22;
SQL
1SELECT a _group
2 , b _aggregate
3 , (
4 SELECT coalesce( min(i) - 1 + ( min(i) = 0 )::int
5 , b[ array_upper( b, 1 ) ]
6 )
7 FROM generate_series( 0, b[ array_length( b, 1 ) ] )
8 as nums(i)
9 WHERE NOT array[i] <@ b
10 ) _result
11FROM
12(
13 VALUES
14 ( 1, array[0,1,2,4,5]::int[] )
15 , ( 2, array[0,1,2,3]::int[] )
16 , ( 3, array[0,1,5]::int[] )
17 , ( 4, array[0,1]::int[] )
18 , ( 5, array[0,1,2,5]::int[] )
19 , ( 6, array[1,2,3]::int[] )
20) q ( a, b )
21ORDER BY 1
22;
SQL
1SELECT a _group
2 , b _aggregate
3 , coalesce(
4 min( coalesce( b[ d - 1 ], 0 ) ) filter( where d - c != 1 )
5 , max( c )
6 ) _result
7FROM
8(
9 VALUES
10 ( 1, array[0,1,2,4,5]::int[] )
11 , ( 2, array[0,1,2,3]::int[] )
12 , ( 3, array[0,1,5]::int[] )
13 , ( 4, array[0,1]::int[] )
14 , ( 5, array[0,1,2,5]::int[] )
15 , ( 6, array[1,2,3]::int[] )
16) t1 ( a, b )
17, LATERAL unnest( b ) with ordinality t2 ( c, d )
18GROUP BY a, b
19ORDER BY 1
20;