A
A
Andrew2012-04-17 12:47:25
PostgreSQL
Andrew, 2012-04-17 12:47:25

postgresql group by

Good afternoon!
There is a table order: id | customer_id | created | category_id
There is a query select customer_id, date_trunc('day', min("order".created)) as created from "order" group by 1
It correctly selects the data that is needed, in fact, the user ID with the minimum date of his order.
It is necessary to pull out another category_id
That is,
select customer_id, date_trunc('day', min("order".created)) as created, category_id from "order" group by 1,3
such a query gives side rows, you need to select the category_id of that order, from which min("order".created)
Can you tell me how?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
alexius2, 2012-04-17
@alexius2

Through DISTINCT should work:

select distinct on (customer_id) customer_id, date_trunc('day', «order».created) as created, category_id from «order» order by 1, «order».created DESC

A
AxisPod, 2012-04-17
@AxisPod

group by in this case reduces how it lies in the database, as I understand it, you probably need to look in the direction of having. www.postgresql.org/docs/8.1/static/tutorial-agg.html

Z
ztxn, 2012-04-17
@ztxn

select the category_id of the order that has min("order".created)

select customer_id, created, category_id 
from 
  (select customer_id, date_trunc('day', «order».created) as created, category_id 
          ,row_number() over (partition by customer_id order by date_trunc('day', «order».created)) rn
   from «order»)s
where rn = 1

K
kuzemchik, 2012-04-17
@kuzemchik

select distinct on(customer_id) customer_id,category_id,date_trunc('day', min(created)) as createdon from testtable group by customer_id,category_id order by customer_id,createdon

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question