在同一列中除以两个特殊值

时间:2019-09-30 09:36:46

标签: mysql sql-server

我想从一列中将两个值相除,如下所示:

enter image description here

实际上,我希望将阻止的呼叫除以呼叫尝试,然后得出百分比。

我使用下面的代码,答案是可以的:

选择 round((cast(100 *(从dbo中选择count(event)作为EventCount。['New ST $'] where event ='Blocked Call')as float))      /(cast((从dbo中选择count(event)作为EventCount。['New ST $'],其中event ='Call Attempt')为float)),3) 为“ BCR(%)”

感谢@GMB

1 个答案:

答案 0 :(得分:0)

使用内联查询:

SELECT 
    100.00 * (SELECT eventCount FROM mytable WHERE event = 'Blocked Call')
        / (SELECT eventCount FROM mytable WHERE event = 'Call Attempt')

或使用聚合:

SELECT 
    100.00 * MAX(CASE WHEN event = 'Blocked Call' THEN eventCount END)
        / MAX(CASE WHEN event = 'Call Attempt' THEN eventCount END)
FROM mytable

修改

您显示的数据似乎已经是聚合查询的结果。您可以通过直接查询初始表来获得预期的结果,例如:

SELECT 
    100.00 * SUM(CASE WHEN event = 'Blocked Call' THEN 1 ELSE 0 END)
        / SUM(CASE WHEN event = 'Call Attempt' THEN 1 ELSE 0 END)
FROM mytable
WHERE event IN ('Blocked Call', 'Call Attempt')