SELECT array_agg(DISTINCT type) AS types,
MIN(value) AS min,
MAX(value) AS max
FROM your_table
Postgres: get min, max, aggregate values in one select
-
12-06-2023 - |
Question
I am using Postgresql 8.4. I have a table like this:
type | value
------+-------
1 | 5
2 | 6
1 | 4
3 | 10
I want to write one select that will give me the minimum & maximum value, and an aggregate of all the types as integer[]
. The desired result should be:
min | max | types
-----+-----+-----------
4 | 10 | {1, 2, 3}
To get the min and max, I already have:
SELECT MIN(value) min, MAX(value) max FROM table;
To get the types in a standalone select, I use:
SELECT array_agg(DISTINCT type) types FROM table;
How can I combine these into one select (that is not too inefficient)?
Solution
OTHER TIPS
Try this query:
SELECT * FROM
(SELECT MIN(value),MAX(value) FROM table1)t1,
(SELECT array_agg(DISTINCT type) FROM table1)t2;
SQL Fiddle
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow