内部子查询需要检查同一组,但不能跨所有组检查

时间:2013-10-11 19:19:35

标签: sql sql-server

Select GroupId,count(distinct GroupProgramYearParticipantID)as [ChildAddedcurrent]  
from #temp1 
Where (MonthFlag = 0) and (ParticipantTypeName = 'child')  
and (GroupProgramYearParticipantID not in 
(Select distinct GroupProgramYearParticipantID 
from #temp1 
Where (MonthFlag = 1) and (ParticipantTypeName = 'child'))) 
group by groupId

内部选择查询检查表中的所有groupid,但我希望它检查外部select查询中引用的每个对应组。

1 个答案:

答案 0 :(得分:0)

您需要在子查询中添加一个where子句,以便通过groupId引用主体查询,以获得您正在寻找的结果。

Select GroupId,count(distinct GroupProgramYearParticipantID)as [ChildAddedcurrent]  
from #temp1 
Where (MonthFlag = 0) and (ParticipantTypeName = 'child')  
and (GroupProgramYearParticipantID not in 
(Select distinct GroupProgramYearParticipantID 
from #temp1 t
Where (t.MonthFlag = 1) and (t.ParticipantTypeName = 'child') and t.GroupId = GroupId)) 
group by groupId