# 9.24. 返回集合的函数

`generate_series(start, stop)`intbigintsetof intsetof bigint (与参数类型相同) 生成一个数值序列，从startstop，步长为 1 。
`generate_series(start, stop, step)`intbigintsetof intsetof bigint (与参数类型相同) 生成一个数值序列，从startstop，步长为step
`generate_series(start, stop, step interval)`timestamptimestamp with time zonesetof timestampsetof timestamp with time zone (与参数类型相同) 生成一个数值序列，从startstop，步长为step

```SELECT * FROM generate_series(2,4);
generate_series
-----------------
2
3
4
(3 rows)

SELECT * FROM generate_series(5,1,-2);
generate_series
-----------------
5
3
1
(3 rows)

SELECT * FROM generate_series(4,3);
generate_series
-----------------
(0 rows)

-- this example relies on the date-plus-integer operator
SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a);
dates
------------
2004-02-05
2004-02-12
2004-02-19
(3 rows)

SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
'2008-03-04 12:00', '10 hours');
generate_series
---------------------
2008-03-01 00:00:00
2008-03-01 10:00:00
2008-03-01 20:00:00
2008-03-02 06:00:00
2008-03-02 16:00:00
2008-03-03 02:00:00
2008-03-03 12:00:00
2008-03-03 22:00:00
2008-03-04 08:00:00
(9 rows)```

`generate_subscripts(array anyarray, dim int)`setof int 生成一系列包括给定数组的下标。
`generate_subscripts(array anyarray, dim int, reverse boolean)`setof int 生成一系列包括给定数组的下标。当reverse为真时， 该系列则以相反的顺序返回。

`generate_subscripts`是一个为给定数组中的指定维度生成有效下标集的便利函数。 如果数组中没有所请求的维度或者NULL数组，返回0行（但是会给数组元素为空的返回有效下标）。 下面一些例子：

```-- basic usage
SELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;
s
---
1
2
3
4
(4 rows)

-- presenting an array, the subscript and the subscripted
-- value requires a subquery
SELECT * FROM arrays;
a
--------------------
{-1,-2}
{100,200,300}
(2 rows)

SELECT a AS array, s AS subscript, a[s] AS value
FROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;
array     | subscript | value
---------------+-----------+-------
{-1,-2}       |         1 |    -1
{-1,-2}       |         2 |    -2
{100,200,300} |         1 |   100
{100,200,300} |         2 |   200
{100,200,300} |         3 |   300
(5 rows)

-- unnest a 2D array
CREATE OR REPLACE FUNCTION unnest2(anyarray)
RETURNS SETOF anyelement AS \$\$
select \$1[i][j]
from generate_subscripts(\$1,1) g1(i),
generate_subscripts(\$1,2) g2(j);
\$\$ LANGUAGE sql IMMUTABLE;
CREATE FUNCTION
postgres=# SELECT * FROM unnest2(ARRAY[[1,2],[3,4]]);
unnest2
---------
1
2
3
4
(4 rows)```