HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

sum() of column by distinct() id column

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
distinctcolumnsum

Problem

I have the following query:

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`


I need the sum(leads.source_cost) to use distinct leads.id in my query because a lead can be assigned more than once.

How do I do this? I can't do a group by because I need the group by to use the date alias.

Solution

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

Here is a blog post that describes exactly this situation and provides a very nice solution to it, using a simple formula:

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

Context

StackExchange Database Administrators Q#184312, answer score: 6

Revisions (0)

No revisions yet.