从具有多个where子句的多个表中进行选择

时间:2012-08-13 09:29:14

标签: sql stored-procedures

我正在尝试编写一个存储过程,该过程将计算表中未删除的所有案例,按另一个表中的CaseStatusID分组,但只有{{1也没有被删除。我还希望它返回任何没有相关案例的CaseStatusID(即数为0)

到目前为止,我已经尝试了

CaseStatusID

AND

这将返回正确的案例,但不包括任何计数为0的CaseStatusDesc

    Create Table #tCaseStatus   (CaseStatusID int,CaseStatusDesc varchar(200) )
declare @NofCases int
declare @CaseStatusID int
declare @CaseStatusDesc varchar(200)

BEGIN
    INSERT #tCaseStatus 
    Select CaseStatusID, CaseStatusDesc From dbo.CaseStatus Where IsDeleted = 0
    Select @NofCases = Count(*) From #tCaseStatus
    While (@NofCases > 0)
    Begin
        Select Top (1) @CaseStatusID = CaseStatusID, @CaseStatusDesc = CaseStatusDesc from #tCaseStatus 
        SELECT    CaseStatusDesc, Count(CaseID) AS CountCases
        FROM      Cases inner join #tCaseStatus on Cases.CaseStatusID = #tCaseStatus.CaseStatusID
        WHERE     (IsDeleted = 0) AND Cases.CaseStatusID = @CaseStatusID
        Group by  #tCaseStatus.CaseStatusDesc
        Set @NofCases = @NofCases - 1
        Delete Top(1) from #tCaseStatus
    End
END

这将返回所有CaseStatusDesc甚至是已删除的那些

SELECT     CaseStatus.CaseStatusDesc, COUNT(Cases.CaseID) AS CaseCount
FROM         Cases FULL OUTER JOIN
                  CaseStatus ON Cases.CaseStatusID = CaseStatus.CaseStatusID
WHERE     (CaseStatus.IsDeleted = 0) AND
                  (Cases.IsDeleted = 0)
GROUP BY CaseStatus.CaseStatusDesc, CaseStatus.CaseStatusID
ORDER BY CaseStatus.CaseStatusID

但我似乎无法获得理想的结果

1 个答案:

答案 0 :(得分:1)

这就是你要追求的吗?

select 
    casestatus.casestatusid,
    casestatusdesc,
    COUNT(caseid)
from casestatus
    left join cases 
        on casestatus.casestatusid = cases.casestatusid
        and cases.isdeleted=0
where
    casestatus.isdeleted=0
group by    
    casestatus.casestatusid,
    casestatusdesc