2011-03-08 21 views
1

我有如下因素表使用方法: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,编辑数的情况下,而不是responsibles,希望这是确定:) – Andomar 2011-03-08 11:01:49

+0

你大概的意思,COUNT(DISTINCT c.CaseID)。有趣的答案。 – MichaelD 2011-03-08 11:02:08

+0

@Michael,@Andomar敲你自己:) – 2011-03-08 11:05:10