sql抓取具有相同第二列的重复记录

时间:2014-01-17 19:06:32

标签: sql sql-server

我正在尝试在sql server中编写一个查询:

表:

 SELECT [Id]
         ,[BrokerId]
         ,[UserId]
      FROM [UserBroker]

我想抓住的价值观点:

Id  BrokerId    UserId
21288   252055  223177
21291   252055  223178

尝试查询:

我想抓取所有具有重复用户ID的记录到一个brokerid。我尝试过这个查询但不正确:

 SELECT 
  [BrokerId]
  ,[UserId]
 FROM [UserBroker]
 group by [BrokerId],[UserId]
 having count([BrokerId]) = 1 and count([UserId]) > 1

3 个答案:

答案 0 :(得分:1)

Select UB.ID, UB.BrokerID, UB.userId
FROM userBroker ub
INNER JOIN userBroker mUB
 on Ub.BrokerID = mub.BrokerID
 and Ub.userID <> mub.UserID
GROUP BY UB.ID, UB.BrokerID, UB.userId
ORDER BY UB.BrokerID, UB.userId, UB.Id

返回ID,broker和userID,其中同一代理存在不同的userID。请注意,如果数据中存在重复项,则使用group by(对于不同的ID,存在相同的brokerID和userId)

用于使副本更容易找到的顺序;他们应该在彼此之后。

答案 1 :(得分:0)

这将返回与多个不同UserId相关的所有BrokerId:

SELECT 
 [BrokerId]
FROM [UserBroker]
group by [BrokerId]
having count(*) > 1
   and count(distinct [UserId]) > 1

如果没有关于您的数据或结构的更多信息,count(distinct [UserId]) > 1可能过多(是否真的可以将BrokerId多次关联到同一个UserId?)。

答案 2 :(得分:0)

WITH t AS (
  SELECT *,
    COUNT(*) OVER(PARTITION BY [BrokerId], [UserId]) c
  FROM [UserBroker]
)
SELECT [Id], [BrokerId], [UserId]
FROM t
WHERE c > 1