我将您所说的解释为:“并且用户名与主要名称不同”。
所以,问题是找到最常见的名称,然后找到除该名称之外的所有其他行。
with tgrp as (select tu.userid, tu.username, count(*) as cnt
from tblUser tu
group by tu.userid, tu.username
),
tmax as (select tu.userid, tu.username, cnt
from tgrp join
(select tu.userid, max(cnt) as maxcnt
from tgrp
group by tu.userid
) t1
on tgrp.userid = t1.userid and tgrp.cnt = t1.maxcnt
)
select *
from tblUser tu left outer join
tmax
on tu.userid = tmax.userid and tu.username = tmax.username
where tmax.userid is null
这个查询是一步一步完成的。查找 id 和 name 的所有组合的计数。然后找到最大组合。然后找到不是最大组合的所有内容。
如果您只想要具有多个名称的用户标识,您可以使用:
select userid
from tblUser tu
group by userid
having count(distinct username) > 1
要获取完整记录,请将其连接回原始表:
select *
from tbl_user tu
where tu.userid in (select userid
from tblUser tu
group by userid
having count(distinct username) > 1
)