如何获取具有两种不同值源类型的部件?

How to get Parts that have two different value source type?

我在 sql 服务器 2017 上工作,我需要获得具有 two different source type 的部件 ID 同样 part .

但每个部分有两种不同的源类型

并且它必须有两种源类型中的一种源类型等于 8901。

示例数据

create table #temp
     (
     partid int,
     sourcetypeid int
     )
     insert into #temp(partid,sourcetypeid)
     values
     (1290,5012),
     (1290,5012),
     (1290,8901),
     (3501,5402),
     (3501,74430),
     (7001,8901),
     (7321,8900),
     (2040,5090),
     (2040,5400),
     (7321,7400),
     (9110,8901),
     (9110,8901)

我的尝试

select partid from #temp
 where sourcetypeid=8901
 group by partid
 having count(distinct sourcetypeid)=2

但是 return null

预期结果

partid that have two different source type at least source type 8901 must exist

but it return null

当前查询失败,因为WHERE子句排除了除one之外的所有sourceTypeId:8901.

PartId | SourceTypeId
-----: | -----------:
  1290 |         8901
  7001 |         8901
  9110 |         8901
  9110 |         8901

因此,当 HAVING 子句搜索具有两 (2) 个 SourceTypeId 值的部分时,找不到匹配项,因为计数始终为 1:

PartId | COUNT(DISTINCT t.SourceTypeId)
-----: | -----------------------------:
  1290 |    1
  7001 |    1
  9110 |    1

相反,尝试使用 EXISTS 来确保两个 SourceTypeId 之一是 8901:

SELECT t.PartId
FROM   #temp t 
WHERE  EXISTS (
       SELECT 1
       FROM  #temp r
       WHERE r.SourceTypeId = 8901
       AND   r.partId = t.PartId
)
GROUP BY  t.PartId
HAVING COUNT(DISTINCT t.SourceTypeId)=2

结果:

| PartId |
| -----: |
|   1290 |