我想下面的查詢:很熱將4個查詢結合到一個沒有具有多個條件的子查詢中?
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
Select groupId,count (distinct GroupProgramYearParticipantID) as [CaregiverAddedcurrent]
from #temp1 Where MonthFlag=0 and ParticipantTypeName='caregiver'
and GroupProgramYearParticipantID not in (Select distinct GroupProgramYearParticipantID from #temp1
Where MonthFlag=1 and ParticipantTypeName='caregiver')
group by groupId
Select groupId,count (distinct GroupProgramYearParticipantID) as [ChildAddedprior]
from #temp1 Where MonthFlag=1 and ParticipantTypeName='child'
and GroupProgramYearParticipantID not in (Select distinct GroupProgramYearParticipantID from #temp1
Where MonthFlag=2 and ParticipantTypeName='child')
group by groupId
Select groupId,count (distinct GroupProgramYearParticipantID) as [caregiverAddedPrior]
from #temp1 Where MonthFlag=1 and ParticipantTypeName='caregiver'
and GroupProgramYearParticipantID not in (Select distinct GroupProgramYearParticipantID from #temp1
Where MonthFlag=2 and ParticipantTypeName='caregiver')
group by groupId
更是這樣的:
select groupID,
count(distinct case when MonthFlag=0 and ParticipantTypeName='child'
and GroupProgramYearParticipantID not in (Select distinct GroupProgramYearParticipantID from #temp1
Where MonthFlag=1 and ParticipantTypeName='child') then GroupProgramYearParticipantID end) as [ChildAddedcurrent],
count(distinct case when MonthFlag=0 and ParticipantTypeName='caregiver'
and GroupProgramYearParticipantID not in (Select distinct GroupProgramYearParticipantID from #temp1
Where MonthFlag=1 and ParticipantTypeName='caregiver') then GroupProgramYearParticipantID end) as [CaregiverAddedcurrent],
count(distinct case when MonthFlag=1 and ParticipantTypeName='child'
and GroupProgramYearParticipantID not in (Select distinct GroupProgramYearParticipantID from #temp1
Where MonthFlag=2 and ParticipantTypeName='child')then GroupProgramYearParticipantID end) as [ChildAddedprior],
count(distinct case when MonthFlag=1 and ParticipantTypeName='caregiver'
and GroupProgramYearParticipantID not in (Select distinct GroupProgramYearParticipantID from #temp1
Where MonthFlag=2 and ParticipantTypeName='caregiver') then GroupProgramYearParticipantID end) as [caregiverAddedPrior]
From #temp1
group by groupID
但我得到一個錯誤:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
只是確認預期的結果。在每個查詢中都有一個Where過濾器「和GroupProgramYearParticipantID不在」中。過濾此GroupProgramYearParticipantID的子查詢不考慮GroupID,但Outer Most查詢使用GroupBY GroupID列。你確定在爲IN子句過濾「GroupProgramYearParticipantID」時,結果應該查看所有的GroupID嗎? –
它應該只在相應的組中查找。 – Aditya