Sql server 2008 r2 标识具有链接到唯一值的多个ID的行

Sql server 2008 r2 标识具有链接到唯一值的多个ID的行,sql-server-2008-r2,Sql Server 2008 R2,使用ms sql 2008 r2;我相信这是非常简单的。我试图确定唯一值{ISIN}链接到多个标识符的位置。一个示例输出是: isin entity_id XS0276697439 000BYT-E XS0276697439 000BYV-E 这实际上是一个错误,我想寻找可能有多个实体id链接到唯一ISIN的其他实例 这是我目前的工作,但显然不正确: select isin, entity_id from edm_security_entity_map whe

使用ms sql 2008 r2;我相信这是非常简单的。我试图确定唯一值{ISIN}链接到多个标识符的位置。一个示例输出是:

isin            entity_id
XS0276697439    000BYT-E
XS0276697439    000BYV-E
这实际上是一个错误,我想寻找可能有多个实体id链接到唯一ISIN的其他实例

这是我目前的工作,但显然不正确:

select isin, entity_id from edm_security_entity_map
where isin is not null
--and isin = ('XS0276697439')
group by isin, entity_id
having COUNT(entity_id) > 1
order by isin asc
谢谢你的帮助。

艾略特

现在我面前没有SQL的副本,所以如果我的语法不正确,我深表歉意

我首先要找到重复的:

select
   x.isin
  ,count(*)
from edm_security_entity_map as x
group by x.isin
having count(*) > 1
然后将其连接回完整表,以查找这些副本的来源:

;with DuplicateList as
(
select
   x.isin
  --,count(*)     -- not used elsewhere
from edm_security_entity_map as x
group by x.isin
having count(*) > 1
)
select
   map.isin
  ,map.entity_id
from edm_security_entity_map as map
inner join DuplicateList as dup
  on dup.isin = map.isin;
嗯,, 迈克尔

你的意思是,如果isin-1为实体1和实体2都有一行,这是一个错误,但是isin-3,比如说,在两个分离行中链接到实体3是可以的?丑陋但易读的解决方案是在前一个解决方案上预挂另一个CTE

;with UniqueValues as
(select distinct
   y.isin
  ,y.entity_id
from  edm_security_entity_map as y
)
,DuplicateList as
(
select
   x.isin
  --,count(*)     -- not used elsewhere
from UniqueValues as x
group by x.isin
having count(*) > 1
)
select
   map.isin
  ,map.entity_id
from edm_security_entity_map as map  -- or from UniqueValues, depening on your objective.
inner join DuplicateList as dup
  on dup.isin = map.isin;

在最终查询中使用附加的GROUPBY子句有更好的解决方案。如果这是投入生产,我会推荐。或者如果您的表有无数行。如果您只需要做一些分析,我希望上面的内容就足够了。

谢谢Michael;差不多了。它还返回相同的多个实体ID链接到ISIN的位置,这是确定的。这是实体ID不同的地方,我想隔离事件。我对上面的代码做了轻微的修改。