mysql group by正确的总和和丢失的数据问题

时间:2015-03-24 20:18:15

标签: mysql group-by sum

我正在尝试为每个campaign_name生成结果报告,并总计totalCommissions和totalDeposit金额, 金额为十进制8,2格式。

返回的结果不是我所期望的。 感谢

select t.campaign_name, 
       count(distinct t.uuid) as visits, 
       count(distinct l.uuid) as leads,
       count(distinct r.uuid) as registrations,
       count(distinct c.uuid) as ftd,
       sum(amount) as totalCommissions,
       sum(deposit_amount) as totalDeposits 
from trackings as t  
    left join (
       select uuid 
       from leads 
       where leads.lead = 1
    ) as l on l.uuid = t.uuid 
    left join (
       select uuid 
       from registrations 
       where registrations.registration = 1
    ) as r on r.uuid = t.uuid 
    left join (
       select uuid,
              trader_id 
       from conversions 
       where conversions.ftd = 1
    ) as c on t.uuid = c.uuid 
    left join (
       select trader_id, 
              amount,
               sum(amount) as totalCommissions 
       from affiliate_commissions group by trader_id
    ) as ac on ac.trader_id = c.trader_id 
    left join (
       select transaction_id,
              trader_id, 
              deposit_amount, 
              sum(deposit_amount) as totalDeposits 
       from transactions  
       group by trader_id
    ) as tr on tr.trader_id = c.trader_id 
 where `t`.`created_at` between '2015-03-01 00:00:00' and '2015-03-24 23:59:59' 
    and `aff_id` = '2' 
 group by `t`.`campaign_name'

预期结果应按campaign_name聚合:

created_at,campaign_name,visits,leads,registrations,ftd,totalDeposits,totalCommissions
2015-03-17 23:50:11,defaul,2,2,2,2,1100.00,4.32
    2015-03-15 18:25:38,new_campaign_name,1,1,1,1,300.00,
    2015-03-18 10:44:48,new_test,1,0,0,0,,

当前输出结果:

created_at,campaign_name,visits,leads,registrations,ftd,totalDeposits,totalCommissions
2015-03-17 23:50:11,defaul,2,2,2,2,100.00,
2015-03-15 18:25:38,new_campaign_name,1,1,1,1,300.00,
2015-03-18 10:44:48,new_test,1,0,0,0,,

0 个答案:

没有答案