sum() 按 distinct() id 列的列

kjd*_*n84 4 mysql

我有以下查询:

select 
    sum(leads.source_cost) as cost, 
    coalesce(sum(assignments.recipient_revenue), 0) as revenue, 
    (coalesce(sum(assignments.recipient_revenue), 0) -
              sum(leads.source_cost)) as profit, 
    date_format(leads.updated_at, "%m/%d/%Y") as date 
from `leads` 
left join `assignments` on `assignments`.`lead_id` = `leads`.`id`
                       and `assignments`.`deleted_at` is null 
where leads.updated_at between "2017-08-24 04:00:00"
                           and "2017-08-26 03:59:59" 
group by `date`
Run Code Online (Sandbox Code Playgroud)

我需要在查询中sum(leads.source_cost)使用 distinct leads.id,因为可以多次分配潜在客户。

我该怎么做呢?我不能做 group by 因为我需要 group by 才能使用date别名。

小智 6

https://tiaashish.wordpress.com/2014/01/31/mysql-sum-for-distinct-rows-with-left-join/

这是一篇博客文章,它使用一个简单的公式准确描述了这种情况并提供了一个非常好的解决方案:

SUM(leads.source_cost) * COUNT(DISTINCT leads.id) / COUNT(*)


归档时间:

查看次数:

11058 次

最近记录:

6 年,10 月 前