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
  • 605,456
  • 145
  • 1,078
  • 1,228
Prabhakaran
  • 3,900
  • 15
  • 46
  • 113

4 Answers4

5
select distinct on (customer_id)
    customer_id, id, created_at
from thunderbolt_orders
order by customer_id, id
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
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
  • 107,110
  • 28
  • 195
  • 197
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,536
  • 5
  • 36
  • 57
Salil
  • 46,566
  • 21
  • 122
  • 156
  • @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
  • 630
  • 2
  • 7
  • 17