sql-选择计数相等的用户对

rryofs0p  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(562)

我正在尝试编写一个查询,返回具有相同贷款数量的成对用户。
我有这张table:
贷款

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

这是我的代码如何获得成对的用户:

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;

这是我想要从我的查询,但我不知道如何在正确的方式比较两个计数,我试过,但没有工作。

id_user1   id_user2  number_loan
 1            2           2
 3            4           1
knpiaxh1

knpiaxh11#

最合理的方法是在加入之前将贷款汇总:

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;

您可以在不进行预聚合的情况下执行此操作,但查询的成本将高得多:

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);

我不推荐这种方法。

相关问题