PostgreSQL - Функция ARRAY_AGG ()
Функция PostgreSQL ARRAY_AGG () - это агрегатная функция, которая принимает набор значений и возвращает массив, в котором каждое значение во входном наборе присваивается элементу массива.
Синтаксис: ARRAY_AGG (выражение [ORDER BY [sort_expression {ASC | DESC}], [...])
TheORDER BY clause is an voluntary clause. It specifies the order of rows that are processed in the collection, which establishes the order of the elements in the result array. It is often used with the GROUP BY clause.
Now let’s look into some examples.
Example 1:
We will be using the film
, film_actor
and actor
tables in the dvdrental sample database for demonstration. In this example we will query for the list of film title and a list of actors for each film using the ARRAY_AVG() function as follows:
SELECT title, ARRAY_AGG (first_name || " " || last_name) actors FROM film INNER JOIN film_actor USING (film_id) INNER JOIN actor USING (actor_id) GROUP BY title ORDER BY title;
Выход:
Пример 2:
здесь мы будем использовать функцию ARRAY_AGG (), чтобы вернуть список фильмов и список актеров для каждого фильма, отсортированный по имени актера, используя следующие команды:
ВЫБРАТЬ заглавие, ARRAY_AGG ( first_name || '' || фамилия СОРТИРОВАТЬ ПО имя ) актеры ИЗ фильм ВНУТРЕННЕЕ СОЕДИНЕНИЕ film_actor USING (film_id) ВНУТРЕННЕЕ ПРИСОЕДИНЕНИЕ ГРУППА ПО заглавие СОРТИРОВАТЬ ПО заглавие;
Выход: