2016-10-24 15 views
1

我有這樣PostgreSQL的 - 返回(N)的行的每個ID

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 

我想通過PHONE_NUMBER僅返回3個數字的每個CONTACT_ID的,順序,像這樣的表:

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; 

回答

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;