2011-03-08 26 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