2011-03-08 4 views
1

"())에 열이"나는 folowing 테이블이 하위 쿼리 +에서 사용하는 : 나는 그들의 건수와 모든 responsibles의 목록을 할SQL 사용 그룹화 값은

Case with columns > ID,ResponsibleID 
Action with columns > ID,CaseID,Action 

을 자신의 이 모든 경우에 걸친 총 행동 수. 이 일 경우

이 쿼리가 될 수 있지만, 대신 responsibles의 경우를 계산 편집하지

Select 
    Case.ResponsibleID, 
    CaseCount=count(*), 
    --how can i tell sql that this is the CaseID sublist of the group? 
    --It would be possible with a subquery, but i rather not do that for performance reasons. 
    --the real query gets the caseID list from a table 3 or 4 joins later. 
    ActionCount=(select count(*) from Action where CaseID in Case.CaseID) 
From Case 
Group by ResponsibleID 

답변

1
SELECT c.ResponsibleID 
     , COUNT(DISTINCT c.ID) 
     , COUNT(*) 
FROM Case c 
     LEFT JOIN Action a ON a.CaseID = c.CaseID 
GROUP BY 
     c.ResponsibleID 
+0

+1, 즉 DISTINCT ( – Andomar

+0

당신은 아마 의미 : 확인 COUNT 희망하지 c.CaseID). 흥미로운 대답. – MichaelD

+0

@Michael, @Andomar는 자신을 노크합니다. –