Lets say we have 3 columns, all integers, the first the id
, the second X
and the third Y
, where X
is 1
when an instance occurred, 0
when not, and Y
is 1
when an opportunity for that instance occurred and 0
when not.
=================
| id | X | Y |
=================
| 1 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
| 2 | 0 | 0 |
| 2 | 0 | 1 |
| 2 | 1 | 1 |
| .... | | |
=================
What I want to do is go through and find basically X / Y
as a percentage
i.e:
(total number of times an instance occurred / total number of opportunities for that to occur, and this all to be grouped by id) * 100
The query I have which works (but I wonder if there is a more efficient method) is
select id, (CASE WHEN ( sum(Y)) <> 0 THEN ((sum(X))/( sum(Y))) ELSE 0 END) ) * 100) from table GROUP BY id
I wonder if it is more efficient to some how do
sum(cast(case where Y <> 0 THEN (X/Y) ELSE 0 END 0...