通过将sum(case)语句中的两列分开来获取百分比

时间:2012-04-22 06:23:22

标签: sql tsql case aggregate

我尝试添加两列的结果,并根据总列进行计算到下面查询中的“开启时间”列。我想要的结果就是这些专栏:

评估师'OntimeSum''PastDueSum''Ontime + pastdue''%ontime'

我已经在下面的查询中有前三个,但我不知道如何做其他人,似乎无法解决它们或在任何地方找到示例。

WITH AppraiserTurnTime AS
(SELECT (v.ContactLastName+ ', ' +v.ContactFirstName) AS Appraiser

   ,SUM(CASE WHEN oi.SubmittedDate <= oi.AssignedDate THEN 1 ELSE 0 END) AS OnTime
   ,SUM(CASE WHEN oi.SubmittedDate >= oi.AssignedDate THEN 1 ELSE 0 END) AS PastDue


FROM OrderItems oi
JOIN Vendors v ON v.VendorID = oi.VendorID
JOIN VendorClasses vc ON vc.VendorClassID = v.VendorClassID

WHERE vc.VendorClassID in (6, 3)
GROUP BY ContactFirstName,v.ContactLastName)

SELECT * FROM AppraiserTurnTime

1 个答案:

答案 0 :(得分:0)

你已经得到了它。

(2)   ,SUM(CASE WHEN oi.SubmittedDate <= oi.AssignedDate THEN 1 ELSE 0 END) AS OnTime
(3)   ,SUM(CASE WHEN oi.SubmittedDate >= oi.AssignedDate THEN 1 ELSE 0 END) AS PastDue

总计将为(2)+(3),%正常运行时间为(2)/((2)+(3))

您可以为每个指标插入上面(2)和(3)的查询,或者如果需要,可以创建嵌套查询,以便引用列,即

SELECT ..., OnTime+PastDue, etc.
FROM ( your original query)

此外,当前查询将超额计算,因为您同时使用&gt; =和&lt; =。最好确定在确切时间发生的事情是否过期。