Sql 仅统计未在早期组中统计的id
如果groupID 1具有GroupProgramYearParticipanId的1,2,2,3,4,4 GroupID2有GroupProgramYearParticipanId的2,4,4,5,5,6,7 上述查询返回Sql 仅统计未在早期组中统计的id,sql,sql-server,tsql,Sql,Sql Server,Tsql,如果groupID 1具有GroupProgramYearParticipanId的1,2,2,3,4,4 GroupID2有GroupProgramYearParticipanId的2,4,4,5,5,6,7 上述查询返回 Select GroupId, count(distinct GroupProgramYearParticipantID)as [ChildAddedprior] from #temp1 Where (MonthFlag =
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 ChildAddedprior- 4( which takes 1,2,3,4)
DroupID-2 ChildAddedPrior- 5(which includes 2,4,5,6,7)
非常感谢您的帮助您可以使用两个查询来实现这一点 在临时表中选择第一个组的ID 选择第二个组时,不要选择临时表中存在的ID
或者,您可以获取查询ID的结果,并使用公共表表达式从第一个组开始递归地对组进行计数,并从已计数的组中排除项目 这是否满足您的要求
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).
它没有考虑月间隔
select GroupId, count(GPYPId) [Count]
from (
select distinct min(GroupId) GroupId, GroupProgramYearParticipantID GPYPId
from #temp1
group by GroupProgramYearParticipantID
) tblA
group by GroupId;
呵呵,欢迎来到SO!一个问题通常在最初发布后的几分钟内得到最多的关注,因此一定要使用预览和降价帮助,使其尽可能可读、易懂和完整,以最大限度地发挥作用。实际上,一般来说,没有这种可能性,尝试回答以下问题:sql server将如何理解groupid2应该从groupid1中排除数据,或者反之亦然?如果不是一般的方法。有没有这样做的方法?只有两个GroupID吗?不是只有两个,可能有很多。例如刚才提到的2。这不合适,因为我的组数不只是2。好的,看看我的替代方法
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