SQL Group By可能的子查询?

时间:2012-07-16 19:16:07

标签: sql select group-by

我有一个User表,有1个用户关系的记录。我想找到UserId相同且UserName不同的所有记录。

例如我尝试过:

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

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

所以我想要的输出是

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
                   )

答案 2 :(得分: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)