您需要添加显式类型转换以避免错误。'Common'
只是一个字符串文字,Postgres 希望您提供它应该转换为的类型。
您还需要将( returns ) 中的bigint
数字转换为(或有损浮点类型),以从您的除法中获得有意义的结果。然后,您将对该功能感兴趣。num.new_driver_form
count()
bigint
numeric
round()
SELECT num.description
,(num.new_driver_form::numeric / denom.form_sent_to) AS conversion
FROM (
SELECT 'Common'::text AS description
,count(DISTINCT u1.user_id) AS new_driver_form
FROM user_tags u1
JOIN user_tags u2 USING (user_id)
WHERE u1.name = 'sentForm'
AND u2.name = 'recForm'
) num
JOIN (
SELECT 'Common'::text AS description
,count(DISTINCT user_id) AS form_sent_to
FROM user_tags
WHERE name = 'sentForm'
) denom ON num.description = denom.description
当然,您JOIN
一开始并没有多大意义,因为第二个子查询计算单行并且 JOIN 条件始终为TRUE
. 可以简化为:
SELECT num.description
,(num.new_driver_form::numeric / denom.form_sent_to) AS conversion
FROM (
SELECT 'Common'::text AS description
,count(DISTINCT u1.user_id) AS new_driver_form
FROM user_tags u1
JOIN user_tags u2 USING (user_id)
WHERE u1.name = 'sentForm'
AND u2.name = 'recForm'
) num
JOIN (
SELECT count(DISTINCT user_id) AS form_sent_to
FROM user_tags
WHERE name = 'sentForm'
) denom ON TRUE
或者只使用子查询:
SELECT 'Common'::text AS description
,(count(DISTINCT u1.user_id)::numeric
/ (SELECT count(DISTINCT user_id)
FROM user_tags
WHERE name = 'sentForm')) AS conversion
FROM user_tags u1
JOIN user_tags u2 USING (user_id)
WHERE u1.name = 'sentForm'
AND u2.name = 'recForm'