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

如果 groupID 1 具有 GroupProgramYearParticipantID 的 1,2,2,3,4,4 并且 groupID 2 具有 GroupProgramYearParticipantID 的 2,4,4,5,5,6,7

上面的查询返回

GroupID-1 ChildAddedprior- 4( which takes 1,2,3,4)
DroupID-2 ChildAddedPrior- 5(which includes 2,4,5,6,7)

但我想要的是

GroupID-1 ChildAddedprior- 4 (which takes 1,2,3,4)
DroupID-2 ChildAddedPrior- 3 (which includes 5,6,7)(this doesn't include 2,4 which are counted earlier).

非常感谢帮助

4

3 回答 3

1
SELECT GroupID, COUNT(Distinct GroupParticipantID) AS CNT 
FROM #Temp1 A
WHERE A.GroupParticipantID NOT IN
(
SELECT GroupParticipantID 
  FROM #Temp1 B
  WHERE A.GroupID > B.GroupID
)
Group BY GroupID

SQL 小提琴演示

于 2013-10-15T22:05:12.923 回答
0

您可以使用 2 个查询来实现这一点。

  1. 将第一组的 ID 选择到临时表中。

  2. 选择第二组时,不要选择临时表中存在的 id。

或者,您可以获取查询结果(id)并使用公用表表达式从第一个开始递归地计算组,并从您已经计算过的组中排除项目。

于 2013-10-15T21:35:20.333 回答
0

这是否满足您的要求?

select GroupId, count(GPYPId) [Count]
from (
    select distinct min(GroupId) GroupId, GroupProgramYearParticipantID GPYPId
    from #temp1
    group by GroupProgramYearParticipantID
) tblA
group by GroupId;

它没有考虑 MonthFlag。

于 2013-10-15T22:05:12.457 回答