mysql sum行_MYSQL sum()用于不同的行

bd96500e110b49cbb3cd949968f18be7.png

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 conversions,

sum(conversions.value) as conversion_value

FROM links

LEFT OUTER JOIN stats ON links.id = stats.parent_id

LEFT OUTER JOIN conversions ON links.id = conversions.link_id

GROUP BY links.id

ORDER BY links.created desc;

I use DISTINCT because I'm doing "group by" and this ensures the same row is not counted more than once.

The problem is that SUM(conversions.value) counts the "value" for each row more than once (due to the group by)

I basically want to do SUM(conversions.value) for each DISTINCT conversions.id.

Is that possible?

解决方案

I may be wrong but from what I understand

conversions.id is the primary key of your table conversions

stats.id is the primary key of your table stats

Thus for each conversions.id you have at most one links.id impacted.

You request is a bit like doing the cartesian product of 2 sets :

[clicks]

SELECT *

FROM links

LEFT OUTER JOIN stats ON links.id = stats.parent_id

[conversions]

SELECT *

FROM links

LEFT OUTER JOIN conversions ON links.id = conversions.link_id

and for each link, you get sizeof([clicks]) x sizeof([conversions]) lines

As you noted the number of unique conversions in your request can be obtained via a

count(distinct conversions.id) = sizeof([conversions])

this distinct manages to remove all the [clicks] lines in the cartesian product

but clearly

sum(conversions.value) = sum([conversions].value) * sizeof([clicks])

In your case, since

count(*) = sizeof([clicks]) x sizeof([conversions])

count(*) = sizeof([clicks]) x count(distinct conversions.id)

you have

sizeof([clicks]) = count(*)/count(distinct conversions.id)

so I would test your request with

SELECT links.id,

count(DISTINCT stats.id) as clicks,

count(DISTINCT conversions.id) as conversions,

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

FROM links

LEFT OUTER JOIN stats ON links.id = stats.parent_id

LEFT OUTER JOIN conversions ON links.id = conversions.link_id

GROUP BY links.id

ORDER BY links.created desc;

Keep me posted !

Jerome

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值