SUM乘以行数(带连接的查询)

时间:2017-12-14 19:53:02

标签: sql postgresql

我阅读了有关此问题的一些主题,但我找不到在我的代码中使用解决方案的方法。根据我的理解,我做错了。

我在Hubspot CRM中有一堆联系人,其来源标记为Adwords广告系列。我想通过将此广告系列中的广告支出除以生成的潜在客户数来计算潜在客户获取的成本。

问题是,广告花费的总和会乘以特定广告系列的潜在客户数量。

SELECT Sum("adwords"."adwords"."adcost")                           AS 
       "sum", 
       "adwords"."adwords"."campaign"                              AS 
       "campaign", 
       Count(DISTINCT "hubspot_stitch"."contacts"."properties__email__value") AS 
       "Leads", 
       Sum("adwords"."adwords"."adcost") / Count(DISTINCT 
       "hubspot_stitch"."contacts"."properties__email__value")                AS 
       "Cost Per Acquisition" 
FROM   "adwords"."adwords" 
       INNER JOIN "hubspot_stitch"."contacts" 
               ON Lower("adwords"."adwords"."campaign") = 
"hubspot_stitch"."contacts"."properties__hs_analytics_source_data_1__value" 
AND ( ( 
"hubspot_stitch"."contacts"."properties__hs_analytics_source_data_2__value" 
      LIKE 
      'sales_adwords%' ) 
          AND ( 
    "hubspot_stitch"."contacts"."properties__lifecyclestage__value" = 
    'opportunity' 
     OR "hubspot_stitch"."contacts"."properties__lifecyclestage__value" 
        = 
        'customer' ) ) 
GROUP  BY "adwords"."adwords"."campaign" 
ORDER  BY "adwords"."adwords"."campaign" ASC 

这是我收到的结果(示例数字不会丢失我的工作):

Sum        | Campaign       | Leads | Cost Per Acquisition
700,000.00 | [S] mobiledev  | 7     | 100,000.00

但真正的总和应该等于100,000.00(少7倍)

Sum        | Campaign       | Leads | Cost Per Acquisition
100,000.00 | [S] mobiledev  | 7     | 14,285.71

2 个答案:

答案 0 :(得分:1)

所以我真的不知道你的数据是怎么样的,但我猜这个可能有用的东西。但是Tsql语法:

Select (sum(t1.adcost)/count(*)) 'sum' 
  , t1.campaign
  , count(*) 'leads' 
  , (sum(t1.adcost)/count(*))/count(*) 
From (select a.campaign, sum(adCost) ''adcost' from adwords a group by a. Campaign ) t1
-- the rest of your code

上帝,我讨厌在电话上编码。 在我写完这篇文章后,我发现我的commenTip有点不对劲。但这应该这样做

答案 1 :(得分:1)

在不使用JOIN

的单独查询中执行总和
SELECT AD."sum",
       AD."campaign",
       Count(DISTINCT CT."properties__email__value") AS "Leads", 
       AD."sum" / Count(DISTINCT CT."properties__email__value") AS "Cost Per Acquisition" 
FROM
(
    SELECT Sum(AD."adcost")  AS "sum", 
           AD."campaign" AS "campaign"
    FROM   "adwords"."adwords" as AD
    GROUP  BY AD."campaign" 
) as AD
INNER JOIN "hubspot_stitch"."contacts" CT
               ON Lower(AD."campaign") = CT."properties__hs_analytics_source_data_1__value" AND 
( 
    CT."properties__hs_analytics_source_data_2__value" LIKE 'sales_adwords%'  AND 
    ( 
       CT."properties__lifecyclestage__value" = 'opportunity' OR 
       CT."properties__lifecyclestage__value" = 'customer' 
    ) 
) 
GROUP  BY AD."campaign" 
ORDER  BY AD."campaign" ASC