分组与分钟

时间:2013-08-23 12:27:23

标签: sql postgresql greatest-n-per-group

我有下表

enter image description here

我使用了以下查询,我收到了错误消息。我可以确定错误的原因,但我该如何解决?

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

我需要最小id的customer_id和created_at如何实现它。

4 个答案:

答案 0 :(得分:5)

select distinct on (customer_id)
    customer_id, id, created_at
from thunderbolt_orders
order by customer_id, id

答案 1 :(得分: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

答案 2 :(得分:1)

SELECT id,customer_id,created_at 
       FROM thunderbolt_orders 
       WHERE id IN 
       (SELECT MIN(id) FROM thunderbolt_orders GROUP BY customer_id); 

答案 3 :(得分:0)

根据您是否只想要最低身份证,或者您是否想要每个客户的最低身份证,这些都是解决方案。

最低ID:

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

每位客户的最低ID:

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