我有一张这样的表
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}");
答案 0 :(得分:3)
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;