1

I am having the following table

enter image description here

I used following query and i got error message. I can identify why the error is but how can i solve it

select min(id),customer_id,created_at from thunderbolt_orders
  group by customer_id

I need the minimum id's customer_id and created_at how can i achieve it.

Erwin Brandstetter
  • 539,169
  • 125
  • 977
  • 1,137
Prabhakaran
  • 3,819
  • 13
  • 42
  • 104

4 Answers4

5
select distinct on (customer_id)
    customer_id, id, created_at
from thunderbolt_orders
order by customer_id, id
Clodoaldo Neto
  • 108,856
  • 25
  • 211
  • 247
2
with cte as (
    select
        *, row_number() over(partition by customer_id order by id) as row_num
    from Table1
)
select *
from cte
where row_num = 1
Roman Pekar
  • 99,839
  • 26
  • 181
  • 193
1
SELECT id,customer_id,created_at 
       FROM thunderbolt_orders 
       WHERE id IN 
       (SELECT MIN(id) FROM thunderbolt_orders GROUP BY customer_id); 
Naveen Kumar Alone
  • 7,360
  • 5
  • 34
  • 53
Salil
  • 45,112
  • 20
  • 117
  • 151
  • @NaveenKumar:- Have you check my edited answer? I think you are not, which i edited before your answer and comment. – Salil Aug 23 '13 at 12:31
0

Depending on whether or not you just want the minimum ID or whether you want the minimum ID for each customer these are the solutions.

Minimum ID:

select top 1 id,customer_id,created_at from thunderbolt_orders order by id asc

Minimum ID for each customer:

with cte as (
    select min(id) as id
    from thunderbolt_orders 
    group by customer_id
)
select *
from cte c
inner join thunderbolt_orders t on t.id = c.id
Richard Newman
  • 600
  • 2
  • 6
  • 17