PostgreSQL:Division仅返回零

时间:2016-07-22 21:21:10

标签: sql postgresql

我正在尝试动态计算转化率。然而,分裂部分给我带来了一些麻烦。

这是我的代码:

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;

如何以最有效的方式解决此问题?

1 个答案:

答案 0 :(得分:2)

只需将它们转换为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;