左连接和GROUP BY获取不正确的SUM

时间:2015-03-30 18:41:10

标签: mysql group-by left-join

我在总存款总额上得出错误的结果。 我想输出每个campaign_name的总存款报告 并最终在日期范围内。

 SELECT IFNULL(campaign_name,'DIRECT'),
       IFNULL(TotalDeposit,0)
FROM trackings
LEFT JOIN
  (SELECT deposit_amount,
          sum(deposit_amount) AS TotalDeposit,
          uuid
   FROM conversions
   LEFT JOIN transactions ON conversions.trader_id = transactions.trader_id
   WHERE aff_id =3
     AND TYPE='deposit'
   GROUP BY transactions.trader_id) AS conversions ON trackings.uuid = conversions.uuid
WHERE aff_id=3
GROUP BY campaign_name

结果:从trynow广告系列中丢失了200个

campaign_name,TotalDeposit
DIRECT,0.00
new_campaign_name,0.00
test march,500.00
testing,0.00
trynow,800.00

预期结果:

campaign_name,TotalDeposit    
DIRECT,0.00
new_campaign_name,0.00
test march,500.00
testing,0.00
trynow,1000.00

1 个答案:

答案 0 :(得分:0)

我认为您的数据不是很正确 - 使用您提供的数据,测试游行的500存款永远不会被退回,因为它与trader_id 7506相关联,转化表中没有记录。

但是,以下查询更简单易懂,并且正确返回1000 for trynow

SELECT
      IFNULL(SUM(t.deposit_amount),0) AS total_deposits
    , IFNULL(tr.campaign_name,'DIRECT') AS campaign


FROM
    trackings tr            LEFT JOIN

    conversions c ON
        tr.uuid = c.uuid    LEFT JOIN

    transactions t ON
        c.trader_id = t.trader_id AND
        tr.`aff_id` = t.aff_id AND
        t.type = 'Deposit' 

WHERE
    tr.aff_id = 3  AND
    tr.updated_at >= '2015-03-01' AND tr.updated_at < '2015-04-01'

GROUP BY
    IFNULL(tr.campaign_name,'DIRECT')

如果您可以检查所提供的测试数据或以其他方式指向正确的方向,我可能能够改进查询以准确返回您想要的内容。

对于日期过滤,请参阅上面where子句的补充。注意,如果您需要在事务表中过滤日期,则日期过滤子句必须是&#34; on&#34;的一部分。而是声明(因为这个表是左连接的,所以我们不能在主where子句中过滤。)