Reputation: 816
I am trying to calculate conversion rates on the fly. However, the division part is causing me some trouble.
Here is my code:
SELECT
b.owner_id AS "Owner ID",
COUNT(DISTINCT bo.id) AS "Number of Opportunities",
COUNT(DISTINCT CASE WHEN bo.state = 'won' THEN bo.id END) AS "Number of Wins",
(COUNT(DISTINCT CASE WHEN bo.state = 'won' THEN bo.id END) / (COUNT(DISTINCT bo.id)) AS "Inquiry Conversion Rate"
FROM
bookings b
INNER JOIN
booking_opportunities bo
ON (bo.id = b.opportunity_id)
GROUP BY
1;
How do I fix this problem the most efficient way?
Upvotes: 0
Views: 259
Reputation: 7441
Simply cast them to NUMERIC
:
SELECT
b.owner_id AS "Owner ID",
COUNT(DISTINCT bo.id) AS "Number of Opportunities",
COUNT(DISTINCT CASE WHEN bo.state = 'won' THEN bo.id END) AS "Number of Wins",
(COUNT(DISTINCT CASE WHEN bo.state = 'won' THEN bo.id END))::NUMERIC / (COUNT(DISTINCT bo.id))::NUMERIC AS "Inquiry Conversion Rate"
FROM
bookings b
INNER JOIN
booking_opportunities bo
ON (bo.id = b.opportunity_id)
GROUP BY
1;
Upvotes: 2