Postgresql - 每个ID的返回(N)行

时间:2016-10-24 19:50:09

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

我有一张这样的表

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

我想只返回每个contact_id的3个数字,按phone_number排序,如下所示:

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;

请为优化查询。

我的查询

List<string> fruit = new List<string> {"Apple", "Orange", "Pear", "Tomato", "Banana"};
var fruitSentence = fruit.Aggregate((current, next) => $"{current},{next}");

1 个答案:

答案 0 :(得分:3)

使用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;