我有以下查询:
SELECT (COUNT(DISTINCT CASE WHEN houses.level = 'top' THEN users.id END)::float / NULLIF(COUNT(DISTINCT users.id)::float, 0))
FROM users
LEFT JOIN houses ON houses.user_id = users.id
而不是一个比率,我想返回一个百分比,所以我把它改成:
SELECT (COUNT(DISTINCT CASE WHEN houses.level = 'top' THEN users.id END)::float / NULLIF(COUNT(DISTINCT users.id)::float, 0)) * 100
FROM users
LEFT JOIN houses ON houses.user_id = users.id
但是,如果分母 ( NULLIF(COUNT(DISTINCT users.id)::float, 0)
) 返回 null,这意味着我将乘以NULL
* 100。如果分母为 0(因此由于 NULLIF 而为 null),我如何才能不乘以返回 NULL。