SQL - 计算在另一列中有多个输入的用户

SQL - Counting Users That Have Multiple Inputs In Another Column

这应该很容易,我只是卡住了。

我想统计拥有多个账户的用户数量。

示例:

account | user
1         1
2         1
3         1
4         2
5         2
6         3
7         4
8         5
9         6
10        6

这将导致 3 个用户拥有与其用户 ID 关联的多个帐户。

使用 group byhaving。如果您想要拥有多个帐户的用户列表,则:

select user
from mytable
group by user
having count(*) > 1

这假设没有重复 (user, account)。否则,您需要将 having 子句更改为:

having count(distinct account) > 1

或者:

having min(account) <> max(account)

现在,如果您想要此类用户的数量,只需添加另一个聚合级别:

select count(*) cnt
from (
    select user
    from mytable
    group by user
    having count(*) > 1
) t

您可以使用 count(distinct) 过滤:

select count(distinct user)
from t
where exists (select 1
              from t t2
              where t2.user = t.user and t2.account <> t.account
             );