📅  最后修改于: 2023-12-03 14:59:23.076000             🧑  作者: Mango
In PostgreSQL, the array_agg()
function is used to aggregate values into an array. However, if you want to aggregate distinct values only, you need to make use of the DISTINCT
keyword in conjunction with array_agg()
.
Below is an example of how to use array_agg()
with DISTINCT
in SQL:
SELECT array_agg(DISTINCT column_name) AS distinct_array
FROM table_name;
In the above query, replace column_name
with the name of the column containing the values you want to aggregate. Similarly, replace table_name
with the actual name of the table.
The DISTINCT
keyword ensures that only unique values are included in the resulting array.
Here's how you can use it in a practical scenario. Suppose you have a table named employees
with columns like employee_id
, first_name
, and last_name
. If you want to aggregate all distinct last names into an array, you can use the following query:
SELECT array_agg(DISTINCT last_name) AS distinct_last_names
FROM employees;
This query will return an array named distinct_last_names
containing all the unique last names from the employees
table.
Using array_agg()
with DISTINCT
can be handy when you want to condense multiple rows into a single row containing an array of distinct values.
Remember to replace the column_name
and table_name
in the above examples with your actual column and table names, respectively.
Happy coding!