【问题标题】:Postgresql - Return (N) rows for each IDPostgresql - 每个 ID 返回 (N) 行
【发布时间】:2016-10-24 19:50:08
【问题描述】:

我有一张这样的桌子

contact_id |  phone_number 
         1 |  55551002
         1 |  55551003
         1 |  55551000
         2 |  55552001
         2 |  55552008
         2 |  55552003
         2 |  55552007
         3 |  55553001
         3 |  55553002
         3 |  55553009
         3 |  55553004
         4 |  55554000

我只想返回每个contact_id的3个号码,按电话号码排序,如下所示:

contact_id | phone_number
         1 |  55551000
         1 |  55551002
         1 |  55551003
         2 |  55552001
         2 |  55552003
         2 |  55552007
         3 |  55553001
         3 |  55553002
         3 |  55553004
         4 |  55554000

请是一个优化的查询。

我的查询

SELECT a.cod_cliente, count(a.telefone) as qtd
FROM crm.contatos a
  LEFT JOIN (
    SELECT *
    FROM crm.contatos b
    LIMIT 3
  ) AS sub_contatos ON sub_contatos.cod_contato = a.cod_cliente
group by a.cod_cliente;

【问题讨论】:

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


    【解决方案1】:

    使用window functions可以轻松解决此类查询:

    select contact_id, phone_number
    from (
      select contact_id, phone_number, 
             row_Number() over (partition by contact_id order by phone_number) as rn
      from crm.contatos
    ) t
    where rn <= 3
    order by contact_id, phone_number;
    

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 1970-01-01
      • 2015-11-17
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 2021-07-07
      • 1970-01-01
      相关资源
      最近更新 更多