

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 從子查詢建立陣列
<a name="creating-arrays-from-subqueries"></a>

從資料列的集合建立陣列。

```
WITH
dataset AS (
  SELECT ARRAY[1,2,3,4,5] AS items
)
SELECT array_agg(i) AS array_items
FROM dataset
CROSS JOIN UNNEST(items) AS t(i)
```

此查詢會傳回：

```
+-----------------+
| array_items     |
+-----------------+
| [1, 2, 3, 4, 5] |
+-----------------+
```

若要從一組資料列建立一系列的多個唯一值，請使用 `distinct` 關鍵字。

```
WITH
dataset AS (
  SELECT ARRAY [1,2,2,3,3,4,5] AS items
)
SELECT array_agg(distinct i) AS array_items
FROM dataset
CROSS JOIN UNNEST(items) AS t(i)
```

此查詢會傳回下列結果。請注意，無法保證順序。

```
+-----------------+
| array_items     |
+-----------------+
| [1, 2, 3, 4, 5] |
+-----------------+
```

如需有關使用 `array_agg` 函數的詳細資訊，請參閱 Trino 文件中的 [Aggregate functions](https://trino.io/docs/current/functions/aggregate.html) (彙總函數)。