SQL Server 如何在ID完全匹配时选择行

bq3bfh9z  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(158)
userId  Username TypeId StateId
229    Test name   52   2
229    Test name   52   4
229    Test name   53   2
229    Test name   53   4
238    Test name2  52   2
238    Test name2  53   2

大家好,从上表中,我只想返回匹配Typeid(52,53)和stateId(2,4)的结果。结果不应返回Test name2。因为它没有选择stateid 4。请建议查询

select  userId,Appraiser,PropertyTypeId,StateId  from vw_SuggestedAppraisersWithSchedule 
where P PropertyTypeId in (52,53)  and stateid in (2,4)
group by UserId,Appraiser,PropertyTypeId,StateId Having count(propertytypeId)=2 and having count(stateid)=2

例外结果:

userId  Username TypeId StateId
229    Test name   52   2
229    Test name   52   4
229    Test name   53   2
229    Test name   53   4

每个用户都应具有TypeId数据(52,53)和StateId(2,4)行数据
谢谢你的好意,

taor4pac

taor4pac1#

您可以尝试使用 exists 进行关联:

select userid, username, TypeId, StateId 
from t
where StateId in (2,4) and TypeId in (52,53)
and exists(
  select * from t t2 
  where t2.userid = t.userid and t2.stateid != t.stateid
);

相关问题