SQL - 另一个计数的百分比

时间:2014-10-28 21:25:16

标签: sql sql-server count percentage

我试图通过第二次计数获得第一次计数的百分比。换句话说,我想做NbFirstCallResolutions / TotalCases * 100.

SELECT 

(SELECT 
COUNT([Incident].IncidentId)
FROM [Incident],[CaseResolution]
WHERE [Incident].IncidentId = [CaseResolution].RegardingObjectId
AND [CaseResolution].FirstCallResolution = 1
AND [Incident].CreatedOn >= @Parameter_StartDate 
AND [Incident].CreatedOn <= DATEADD(day,1,@Parameter_EndDate)
) AS NbFirstCallResolutions,

(SELECT 
COUNT([Incident].IncidentId) 
FROM [Incident]
WHERE [Incident].CreatedOn >= @Parameter_StartDate 
AND [Incident].CreatedOn <= DATEADD(day,1,@Parameter_EndDate)
) AS TotalCases

--SELECT NbFirstCallResolutions / TotalCases * 100.0

不确定如何接近这个...

1 个答案:

答案 0 :(得分:1)

您的查询应该能够合并如下:

SELECT 
  SUM(coalesce([CaseResolution].FirstCallResolution, 0) / 
  COUNT([Incident].IncidentId) * 100
FROM 
  [Incident]
  left join [CaseResolution] on 
           [Incident].IncidentId = [CaseResolution].RegardingObjectId 
           AND [CaseResolution].FirstCallResolution = 1
WHERE 
  [Incident].CreatedOn >= @Parameter_StartDate 
  AND [Incident].CreatedOn <= DATEADD(day,1,@Parameter_EndDate

请注意,我将1的{​​{1}}值相加,将空值保留为0.这相当于计算行数。

请务必检查您的操作顺序,因为我相信首先会出现乘法,然后是除法。