我正在尝试编写一个存储过程,它将计算表中未删除的所有案例的计数,并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
但我似乎无法得到想要的结果