0

我有一个用户表,其中有很多记录到 1 个用户关系。我想查找所有用户 ID 相同且用户名不同的记录。

例如我试过:

SELECT UserId, UserName, count(*) FROM tblUser
GROUP BY UserId, UserName

这只是给了我一个用户列表,以及他们有多少次拥有 UserId 和 UserName 的独特组合

所以我想要的输出是

UserId    | UserName
----------+-----------
1111      | Bob
1111      | JoeBob
2222      | Jimmy
2222      | ILikeTurtles
4

3 回答 3

3
select *
from tblUser t1
inner join (
  SELECT UserId
  FROM tblUser 
  GROUP BY UserId
  having count(distinct UserName) > 1
) t2
  on t1.UserID = t2.UserID
于 2012-07-16T19:22:26.883 回答
1

我将您所说的解释为:“并且用户名与主要名称不同”。

所以,问题是找到最常见的名称,然后找到除该名称之外的所有其他行。

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
                   )
于 2012-07-16T19:23:28.433 回答
0
select t.userid, t.username
from tbluser t
where exists(select 1 
             from tbluser t2
             where t.userid = t2.userid
               and t.username <> t2.username)
于 2012-07-16T19:44:23.887 回答