0

I have the following query:

SELECT 
num.description,
(num.new_driver_form/denom.form_sent_to) as conversion
FROM
(SELECT
'Common' 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' as description,
count(DISTINCT user_id) as form_sent_to
FROM 
user_tags
WHERE
name = 'sentForm')denom
ON num.description = denom.description

I am receiving an error that "failed to find conversion function from unknown to text", but am not sure what that means.

4

2 回答 2

0

这是简单的方法

SELECT
  'cohort' as description,
  count(DISTINCT u1.user_id) as new_driver_form,
  x.field as field
FROM user_tags u1
JOIN user_tags u2 USING (user_id)
JOIN anothertable X ON x.blah = u1.blah
WHERE  
  u1.name = 'sentForm'
  AND    
  u2.name = 'recForm'

如果字符串来自其中一个表,则如下所示:

SELECT
  <replace with field name> as description,
  count(DISTINCT u1.user_id) as new_driver_form,
  x.field as field
FROM user_tags u1
JOIN user_tags u2 USING (user_id)
JOIN anothertable X ON x.blah = u1.blah
WHERE  
  u1.name = 'sentForm'
  AND    
  u2.name = 'recForm'
于 2013-11-06T00:18:06.967 回答
0

您需要添加显式类型转换以避免错误。'Common'只是一个字符串文字,Postgres 希望您提供它应该转换为的类型。

您还需要将( returns ) 中的bigint数字转换为(或有损浮点类型),以从您的除法中获得有意义的结果。然后,您将对该功能感兴趣。num.new_driver_formcount()bigintnumericround()

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'
于 2013-11-06T00:40:15.647 回答