【问题标题】:Group by clause with min用 min 按子句分组
【发布时间】:2013-08-23 12:27:23
【问题描述】:

我有下表

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

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

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

【问题讨论】:

  • 你得到什么类型的错误?
  • 它只是可能的最低 ID,它是 customer_id 和 created_at,还是每个 customer_id 的最低 ID,然后返回信息

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


【解决方案1】:
select distinct on (customer_id)
    customer_id, id, created_at
from thunderbolt_orders
order by customer_id, id

【讨论】:

    【解决方案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
    

    【讨论】:

      【解决方案3】:
      SELECT id,customer_id,created_at 
             FROM thunderbolt_orders 
             WHERE id IN 
             (SELECT MIN(id) FROM thunderbolt_orders GROUP BY customer_id); 
      

      【讨论】:

      • @NaveenKumar:- 你检查过我编辑的答案吗?我认为您不是,我在您的回答和评论之前对其进行了编辑。
      【解决方案4】:

      根据您是否只需要最小 ID 或是否需要每个客户的最小 ID,这些都是解决方案。

      最小 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-19
        • 2019-04-17
        • 1970-01-01
        • 2016-07-31
        • 2014-02-17
        • 2013-07-30
        • 2015-10-17
        • 2013-01-10
        相关资源
        最近更新 更多