DBE7 DBE7 - 4 months ago 17
SQL Question

PostgreSQL: Division returns zeros only

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?

Answer

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;
Comments