简体   繁体   English

SQL - Select 具有相同数量的用户对

[英]SQL - Select pairs of users with equal count

I'm trying to write a query that returns pairs of users that have the same number of loans.我正在尝试编写一个返回具有相同贷款数量的用户对的查询。

I have this table:我有这张桌子:

LOANS贷款

id_loan  book_barcode id_user
1         123            1
2         321            2
3         456            3
4         678            4
5         721            1
6         934            2

That's my code how to get pairs of users:这是我如何获得成对用户的代码:

SELECT l1.id_user user_1, l2.id_user user_2
FROM loans l1
JOIN loans l2 ON l2.id_user > l2.id_user
GROUP BY l2.id_user, l2.id_user; 

This is what I want from my query, but I don't know how to compare in the right way two counts, I tried but it didn't work.这就是我想从查询中得到的,但我不知道如何以正确的方式比较两个计数,我试过但没有奏效。

id_user1   id_user2  number_loan
 1            2           2
 3            4           1

The most reasonable way is to aggregate the loans before joining:最合理的方法是在加入前汇总贷款:

with u as (
      select id_user, count(*) as num_loans
      from loans l
      group by id_user
     )
select u1.id_user, u2.id_user
from u u1 join
     u u2
     on u1.num_loans = u2.num_loans and u1.id_user < u2.id_user;

You could do this without pre-aggregating, but the query will be much more expensive:您可以在不预先聚合的情况下执行此操作,但查询会更加昂贵:

select u1.id_user, u2.id_user
from loans u1 join
     loans u2
     on u1.id_user < u2.id_user
group by u1.id_user, u2.id_user
having count(distinct u1.id_loan) = count(distinct u2.id_loan);

I don't recommend this approach.我不推荐这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM