找到具有相同foo但不同的boo的记录

时间:2016-09-03 15:48:09

标签: sql sql-server

我希望使用相同的nickname过滤记录,但记录的contactId不同,但我不能。

SELECT
    nickname, contactId, COUNT(*)
FROM
    UserProfileContacts
GROUP BY
    nickname, contactId
HAVING 
    COUNT(*) > 1

这是我期望的结果;

userId A | nickname B | contactId C
userId A | nickname B | contactId D
userId B | nickname C | contactId F
userId B | nickname C | contactId G

2 个答案:

答案 0 :(得分:1)

group by移除contactid,并根据给定的用户ID和昵称计算不同的contactid事件。

SELECT
    userid, nickname, COUNT(distinct contactId) contactid_count
FROM
    UserProfileContacts
GROUP BY
    userid, nickname
HAVING 
    COUNT(distinct contactId) > 1

要选择contactid,请执行

SELECT u.userid,u.nickname,u.contactid 
FROM UserProfileContacts u
JOIN (
SELECT
    userid,nickname
FROM
    UserProfileContacts
GROUP BY
    userid,nickname
HAVING 
    COUNT(distinct contactId) > 1) t ON t.userid = u.userid AND t.nickname = u.nickname

答案 1 :(得分:0)

如果您使用的是sql server,请使用以下查询cte和count()over()..

  ;WITH cte_1
  AS
    ( SELECT *
         , count(contactid) over(partition by    userid,nickname order by userid,nickname) cnt
   FROM UserProfileContacts)
   SELECT DISTINCT userid,nickname,contactId
   FROM cte_1
   WHERE cnt>1