0

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

到目前为止我已经尝试过

    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

这将返回正确的案例,但不包括任何计数为 0 的 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

这将返回所有 CaseStatusDesc,甚至那些被删除的

SELECT CaseStatus.CaseStatusDesc, COUNT(CASE
                                        WHEN CaseStatus.IsDeleted = 0 THEN 'ok'
                                        WHEN Cases.IsDeleted = 0 THEN 'ok'
                                        Else null                                       
                                    END) AS [Case] 
FROM   Cases  FULL OUTER JOIN CaseStatus ON Cases.CaseStatusID = CaseStatus.CaseStatusID
GROUP BY CaseStatus.CaseStatusDesc, CaseStatus.CaseStatusID
Order By CaseStatus.CaseStatusID asc

但我似乎无法得到想要的结果

4

1 回答 1

1

Is this what you're after?

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
于 2012-08-13T10:26:10.723 回答