Take the following table:
CREATE TABLE boxes (
box integer,
color character varying,
size integer,
...
);
where both box
and color
can assume not unique values out of a small
set.
Querying this table with:
SELECT color, box FROM boxes;
the result will be something like:
+-------+-----+
| color | box |
+-------+-----+
| blue | 2 |
| blue | 3 |
| blue | 4 |
| green | 1 |
| green | 3 |
| red | 1 |
| red | 2 |
| red | 2 |
+-------+-----+
Is it possible to query this table in a manner such that the result has two columns, one with an array (or string, or list) with all the different box
values for each distinct color
?
The result should be something like this:
+-------+-----------+
| color | box_types |
+-------+-----------+
| blue | {2,3,4} |
| green | {1,3} |
| red | {1,2} |
+-------+-----------+
where the color
column must contain unique values, and each row must contain only distinct box
numbers in the aggregate column.
Given the non-agnostic character of this question, I would like to collect all the best solutions for the major DBMS. When answering, please specify for which DBMS each query works.