如何获取具有两种不同值源类型的零件?
我在 sql server 2017 上工作,我需要获取具有两种不同源类型
的部件 ID 每个相同的部分
。
但每个部件有两种不同的源类型
,并且它必须具有等于 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
,但它返回 null
预期结果
I work on sql server 2017 i need to get part id that have two different source type
per same part
.
but part have two different source type per part
and it must have one source type from two source type equal 8901 .
sample data
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)
what i try
select partid from #temp
where sourcetypeid=8901
group by partid
having count(distinct sourcetypeid)=2
but it return null
expected result
partid that have two different source type at least source type 8901 must exist
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当前查询失败,因为 WHERE 子句排除了除 one 之外的所有 sourceTypeId:8901。
因此,当 HAVING 子句搜索具有两 (2) 个 SourceTypeId 值的部分时,找不到匹配项,因为计数始终为
1
:相反,请尝试使用 EXISTS 来确保两个 SourceTypeId 之一为 8901:
结果:
The current query fails because the WHERE clause excludes all sourceTypeId except one: 8901.
So when the HAVING clause searches for parts with two (2) SourceTypeId values, no matches are found, because the count is always
1
:Instead, try using EXISTS to ensure that one of two SourceTypeId's is 8901:
Result: