mysql 查询:如何仅按 cpm.ad_id 进行分组并获得所有 cc 的总和?
我有两个表 - cpm
(cc
、ad_id
和 cpm
)和 clicks
(cc
和 ad_id
)。
当我运行:
SELECT cpm.ad_id,
COUNT(clicks.id) * cpm.cpm AS clicks_income
FROM cpm
LEFT JOIN clicks on clicks.ad_id = cpm.ad_id and clicks.cc = cpm.cc
GROUP BY cpm.ad_id, cpm.cc
我得到:
ad_id | clicks_income
---------------------
1 | 271.00
1 | 2.60
2 | 238.00
现在我想要的结果是:
ad_id | clicks_income
---------------------
1 | 273.60
2 | 238.00
如何仅按 cpm
.ad_id
进行分组并获得所有 cc
的总和>?
当我删除 cpm
.cc
时,我得到:
ad_id | clicks_income
---------------------
1 | 273.00
2 | 238.00
I have two tables - cpm
(cc
, ad_id
and cpm
) and clicks
(cc
and ad_id
).
When I run:
SELECT cpm.ad_id,
COUNT(clicks.id) * cpm.cpm AS clicks_income
FROM cpm
LEFT JOIN clicks on clicks.ad_id = cpm.ad_id and clicks.cc = cpm.cc
GROUP BY cpm.ad_id, cpm.cc
I get:
ad_id | clicks_income
---------------------
1 | 271.00
1 | 2.60
2 | 238.00
now the result I want is:
ad_id | clicks_income
---------------------
1 | 273.60
2 | 238.00
How can I group by only cpm
.ad_id
and having the SUM of all cc
?
When I remove the cpm
.cc
I get:
ad_id | clicks_income
---------------------
1 | 273.00
2 | 238.00
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用
COUNT(whatever) * acolumn
,而是使用SUM(AColumn)
。此外,
LEFT JOIN
在这里没有意义,因为不匹配只会将NULL
添加到总和中,这没有多大帮助。Don't use
COUNT(whatever) * acolumn
, useSUM(AColumn)
instead.Also a
LEFT JOIN
doesn't make sense here because a mismatch will just addNULL
to the sum, which isn't very helpful.