MYSQL sum() for distinct rows

前端 未结 8 1844
太阳男子
太阳男子 2020-11-28 04:43

I\'m looking for help using sum() in my SQL query:

SELECT links.id, 
       count(DISTINCT stats.id) as clicks, 
       count(DISTINCT conversions.id) as con         


        
8条回答
  •  长情又很酷
    2020-11-28 05:02

    Jeromes solution is actually wrong and can produce incorrect results!!

    sum(conversions.value)*count(DISTINCT conversions.id)/count(*) as conversion_value
    

    let's assume the following table

    conversions
    id value
    1 5
    1 5
    1 5
    2 2
    3 1
    

    the correct sum of value for distinct ids would be 8. Jerome's formula produces:

    sum(conversions.value) = 18
    count(distinct conversions.id) = 3
    count(*) = 5
    18*3/5 = 9.6 != 8
    

提交回复
热议问题