3

So I have a table that has EMAIL and Order ID.

EMAIL   |   id
--------------
[email protected] |   1
[email protected] |   2
[email protected] |   3

And I need to SELECT it so that I'd have email column that is distinct and ids column that is array of int's

EMAIL   |   ids
--------------
[email protected] |   [1,2]
[email protected] |   [3]

I use PSQL 9.3. I looked at aggregate functions, but since I'm not too good with SQL atm, I didn't really understand them. My code so far is:

SELECT DISTINCT ON (email) email
FROM order
WHERE date > '2013-01-01';

1 Answer 1

3

Use the aggregate function array_agg():

SELECT email, array_agg(id) AS id_array
FROM   "order"
WHERE  date > '2013-01-01'
GROUP  BY email;

Aside: your identifiers ...

Don't use order as table name, it's a reserved word.
Don't use date as column name, it's a reserved word in standard SQL and a basic type name in Postgres.
I wouldn't use id as column name either, that's a common anti-pattern, but "id" is not a descriptive name. Once you join a couple of tables you have n columns named "id" and you need to start dealing out column aliases, not to speak of the confusion it may cause.

Instead, use something like this:

CREATE TABLE order_data (
   order_data_id serial PRIMARY KEY
 , email         text
 , order_date    date
);
Sign up to request clarification or add additional context in comments.

1 Comment

urr.. I was so sure that I tryed that array_agg(id). And thanks for pointers in style. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.